import datetime
import os
import random
import uuid
from django.http import HttpResponse
from django_redis import get_redis_connection
from lxml import etree

import xmltodict
from django.db import transaction
from django.db.models import Q


# Create your views here.
import json
import time

from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

import requests
import pymysql
from mws import mws, Feeds
from redis import StrictRedis
from rest_framework import status
from rest_framework.generics import GenericAPIView, ListAPIView, CreateAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from tomorrow import threads

from amazondatas.serializers import OrderItemForSKUSerializer
from orders.models import Orders, PaymentExecutionDetailItem, OrdersMoney, Address, PaymentMethodDDetails, Invoice, \
    OrdersItemMoney, TaxCollection, ProductInfos, OrderItem, UpdateTime, CustomsDeclarationInfos, Infos, GoodsRank
from orders.serializers import StoreSerializer, OrderListSerializer, UpdateMysqlOrdersSerializers, \
    PaymentMethodDetailsSerializers, OrderTotalSerializers, ShippingAddressSerializers, UpdateMysqlOrdersSerializers2, \
    InvoiceDataSerializer, OrderItemsSerializer2, OrderItemsSerializer1, \
    OrderItemMoneySerializer, ProductInfoSerializer, TaxCollectionSerializer, OrderItemsSerializer3, \
    OrderItemListSerializer, UpdateTimeSerializer, OrderStatuAndTrackingSeiralizer, OrderItemOfOneSerializer, \
    OrderItemDictOfOneSerializer, OrderItemForCustomsDeclarationInfosSerializer, CustomsDeclarationInfosSerializer, \
    OrderAddressSerializer, OrderItemCustomDec, TrackingNumSerializer, OrderItemIdSerializer, \
    CustomsDeclarationAddIdInfosSerializer, OrderInfoSerializer, ExamineSerializer, DealSerializer, ShippedSerializer, \
    OrderFulfillmentSerializer, OrderFulfillmentStoreManagementSerializer, ExportOrdersSerializer, GoodsRankSerializer, \
    GoodsFinanceViewSerializer, GoodsItemSerializer, OrderStatuAndTrackingSeiralizer1, ShippingAddressSerializers1, \
    TQNameSerializer, TrackingNumberSerializer
from store.models import StoreManagement, UserAndStore
from store.serializers import StoreListSerializer
from users.models import User
from vne_erp.settings.dev1 import BASE_DIR
from vne_erp.utils.exceptions import logger

from vne_erp.utils import iosformat
from vne_erp.utils.script_for_xiaomi import ScriptForXiaomi
import string

from vne_erp.utils.user_agent_and_ip_proxy import IP_PROXY_LIST, USER_AGENT_LIST
# Myself
# access_key = 'AKIAJGOQGGTWX4ICHVZQ'  # replace with your access key
# secret_key = 'SjLuwkvF46VCiPzmlFwP8+aPYjA7BNP3IazSyD0l'  # replace with your secret key
# SexDen
access_key = 'AKIAITNXOMXBNOGOAHMQ'  # replace with your access key
secret_key = 'X/Py9553cKqfcDmpP9DVguSE3/i/oVr5RFoHORBh'  # replace with your secret key

marketplaceids = ['A1AM78C64UM0Y8', 'A2EUQ1WTGCTBG2', 'ATVPDKIKX0DER']


# global update_status
# global update_list
# global percent
percent = float()
update_list = list()
update_status = str()


def get_order_item(AmazonOrderId, store_id):
    time.sleep(2)
    """获取单个OrderItem"""
    # try:
    #     order_info = Orders.objects.get(AmazonOrderId=str(AmazonOrderId))
    # except Exception as e:
    #     return Response({'error_msg': str(e) + '1'})

    try:
        store_info = StoreManagement.objects.get(id=store_id)
    except Exception as e:
        return Response({'error_msg': str(e) + "2"})
    # staff_id = store_info.staff

    # try:
    #     staff_info = User.objects.get(id=staff_id.id)
    # except Exception as e:
    #     return Response({'error_msg': str(e) + '3'})

    # staff_name = staff_info.username
    SellerId = store_info.seller_id if store_info.seller_id != '' else ''
    MWSToken = store_info.mws_token if store_info.mws_token != '' else ''
    x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
    orders = x.list_order_items(amazon_order_id=AmazonOrderId)
    response_data = orders.original
    xml_dict = xmltodict.parse(response_data)

    # staff_info = {'staff_id': staff_id.id, 'staff_name': staff_name}
    store_info = {'store_name': store_info.store}
    # xml_dict['staff_info'] = staff_info
    xml_dict['store_info'] = store_info
    xml_dict = xml_dict['ListOrderItemsResponse']['ListOrderItemsResult']['OrderItems']

    return xml_dict


def order_item_data_to_mysql1(data,order_id):

    fields = ['ItemPrice', 'ShippingPrice', 'GiftWrapPrice', 'ItemTax', 'ShippingTax', 'GiftWrapTax',
              'ShippingDiscountTax',
              'ShippingDiscount', 'PromotionDiscountTax', 'PromotionDiscount', 'CODFee', 'CODFeeDiscount']
    for i in fields:
        data[i] = {"CurrencyCode": "USD", "Amount": 0.00}
        item_money_serializer = OrderItemMoneySerializer(data=data[i])
        item_money_serializer.is_valid()
        item_money_serializer.save()
        fields_item_money_id = OrdersItemMoney.objects.all().order_by('-id').first().id
        data[i] = fields_item_money_id

    p_serializer = ProductInfoSerializer(data=data["ProductInfo"])
    p_serializer.is_valid()
    p_serializer.save()
    order_item_money_id = ProductInfos.objects.all().order_by('-id').first().id

    data["ProductInfo"] = order_item_money_id
    data['IsTransparency'] = string.capwords(data['IsTransparency'])
    data['IsGift'] = string.capwords(data['IsGift'])
    data['Order'] = order_id
    # now_time = datetime.datetime.now().strftime("%Y%m%D%H%m%S")[12:]
    now_time = datetime.datetime.now().strftime("%Y%m%D%H%m%S")[12:] + \
               str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
               str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
               str(random.randint(0, 9)) + str(random.randint(0, 9))
    data['MerchantOrderItemID'] = "TQ" + now_time + "2"
    data['MerchantFulfillmentItemID'] = "TQ" + now_time + "4"
    # data['MerchantOrderItemID'] = "TQ" + now_time + "2"
    # data['MerchantFulfillmentItemID'] = "TQ" + now_time + "4"


    serializer = OrderItemsSerializer2(data=data)
    serializer.is_valid(raise_exception=True)
    serializer.validated_data
    serializer.save()


def field_serializer(data):
    """对item_money外键字段字段进行校验"""
    fields = ['ItemPrice', 'ShippingPrice', 'GiftWrapPrice', 'ItemTax', 'ShippingTax', 'GiftWrapTax', 'ShippingDiscountTax',
     'ShippingDiscount', 'PromotionDiscountTaxPromotionDiscount', 'CODFee', 'CODFeeDiscount']

    for i in fields:
        if i in data.keys:
            item_money_serializer = OrderItemMoneySerializer(data=data[i])
            item_money_serializer.is_valid()
            item_money_serializer.save()
            fields_item_money_id = OrdersItemMoney.objects.all().order_by('-id').first().id
            data[i] = fields_item_money_id


def order_item_data_to_mysql2(data,order_id):

    fields = ['ItemPrice', 'ShippingPrice', 'GiftWrapPrice', 'ItemTax', 'ShippingTax', 'GiftWrapTax',
              'ShippingDiscountTax',
              'ShippingDiscount', 'PromotionDiscountTax', 'PromotionDiscount', 'CODFee', 'CODFeeDiscount']
    data_key_list = list()
    for j in data:
        data_key_list.append(j)

    for i in fields:
        if i not in data_key_list:
            data[i] = {"CurrencyCode": "USD", "Amount": 0.00}
        item_money_serializer = OrderItemMoneySerializer(data=data[i])
        item_money_serializer.is_valid()
        item_money_serializer.save()
        fields_item_money_id = OrdersItemMoney.objects.all().order_by('-id').first().id
        data[i] = fields_item_money_id

    produc_serializer = ProductInfoSerializer(data=data["ProductInfo"])
    produc_serializer.is_valid()
    produc_serializer.save()
    order_item_money_id = ProductInfos.objects.all().order_by('-id').first().id
    data["ProductInfo"] = order_item_money_id

    data['IsTransparency'] = string.capwords(data['IsTransparency'])
    data['IsGift'] = string.capwords(data['IsGift'])
    data['Order'] = order_id
    now_time = datetime.datetime.now().strftime("%Y%m%D%H%m%S")[12:] + \
               str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
               str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
               str(random.randint(0, 9)) + str(random.randint(0, 9))
    data['MerchantOrderItemID'] = "TQ" + now_time + "2"
    data['MerchantFulfillmentItemID'] = "TQ" + now_time + "4"

    if "TaxCollection" in data.keys():

        t_serializer = TaxCollectionSerializer(data=data["TaxCollection"])

        t_serializer.is_valid()
        t_serializer.save()
        TaxCollection_id = TaxCollection.objects.all().order_by('-id').first().id
        data["TaxCollection"] = TaxCollection_id
        serializerx = OrderItemsSerializer1(data=data)
        serializerx.is_valid()
        serializerx.save()
        return
    serializerx = OrderItemsSerializer3(data=data)
    serializerx.is_valid(raise_exception=True)
    serializerx.save()


@transaction.atomic
def data_to_mysql1(data,store_id):

    # 传入order_list数据并存入mysql
    save_id = transaction.savepoint()
    try:
        if 'OrderTotal' not in data.keys():
            data['OrderTotal'] = {"CurrencyCode": "USD", "Amount": 0.00}
        data['OrderTotal']['Amount'] = float(data['OrderTotal']['Amount'])
        serializer2 = OrderTotalSerializers(data=data['OrderTotal'])
        serializer2.is_valid(raise_exception=True)
        serializer2.save()
        value_id2 = OrdersMoney.objects.all().order_by('-id').first().id

        # TODO PaymentMethodDetails
        # serializer3 = PaymentMethodDetailsSerializers(data=data['PaymentMethodDetails'])
        # serializer3.is_valid()
        # serializer3.save()
        # value_id3 = PaymentMethodDDetails.objects.all().order_by('-id').first().id
        if 'ShippingAddress' not in data.keys():
            data['ShippingAddress'] = None
        else:
            if 'AddressLine1' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['AddressLine1'] = '暂无'
            if 'AddressLine2' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['AddressLine2'] = '暂无'
            if 'AddressLine3' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['AddressLine3'] = '暂无'
            if 'AddressType' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['AddressType'] = '暂无'
            if 'Country' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['Country'] = '暂无'
            if 'Name' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['Name'] = '暂无'
            if 'District' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['District'] = '暂无'
            if 'Phone' not in data['ShippingAddress'].keys():
                data['ShippingAddress']['Phone'] = '暂无'
            if 'isAddressSharingConfidential' in data['ShippingAddress'].keys():
                data['ShippingAddress']['isAddressSharingConfidential'] = string.capwords(
                    data['ShippingAddress']['isAddressSharingConfidential'])
            try:
                serializer1 = ShippingAddressSerializers(data=data['ShippingAddress'])
                serializer1.is_valid()
                serializer1.save()
            except Exception as e:
                logger.error(e)

                return
            value_id1 = Address.objects.all().order_by('-id').first().id
            data['ShippingAddress'] = value_id1

        now_time = datetime.datetime.now().strftime("%Y%m%D%H%m%S")[12:] +\
                   str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
                   str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
                   str(random.randint(0, 9)) + str(random.randint(0, 9))
        data['MerchantOrderID'] = "TQ" + now_time + "1"
        data['MerchantFulfillmentID'] = "TQ" + now_time + "3"
        data['TQName'] = "TQ" + ''.join(str(uuid.uuid1()).split('-'))[6:20].upper() + ''.join(random.sample(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 5))

        # data['MerchantOrderItemID'] = "TQ" + now_time + "2"
        # data['MerchantFulfillmentItemID'] = "TQ" + now_time + "4"

        # data['PaymentMethodDetails'] = value_id3
        # data['OrderItemId'] = OrderItemId
        data['OrderTotal'] = value_id2
        if 'BuyerName' not in data.keys():
            data['BuyerName'] = '暂无'
        if 'BuyerEmail' not in data.keys():
            data['BuyerEmail'] = '暂无'

        try:
            serializer = UpdateMysqlOrdersSerializers(data=data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        except Exception as e:

            logger.error(e)
            return

    except Exception as e:

        logger.error(e)
        transaction.savepoint_rollback(save_id)

    order_id = Orders.objects.all().order_by("-id").first().id
    xml_dict = get_order_item(data["AmazonOrderId"], store_id)

    if isinstance(xml_dict['OrderItem'], list):


        for j in xml_dict['OrderItem']:
            j['AmazonOrderId'] = data["AmazonOrderId"]
            if j["QuantityOrdered"] == "0":

                order_item_data_to_mysql1(j, order_id)
            else:

                order_item_data_to_mysql2(j, order_id)
    else:
        xml_dict['OrderItem']['AmazonOrderId'] = data["AmazonOrderId"]
        if xml_dict['OrderItem']["QuantityOrdered"] == '0':

            order_item_data_to_mysql1(xml_dict['OrderItem'], order_id)
        else:

            order_item_data_to_mysql2(xml_dict['OrderItem'], order_id)

    transaction.savepoint_commit(save_id)


@transaction.atomic
def data_to_mysql2(data, store_id):

    save_id = transaction.savepoint()
    try:
        """取消的商品也赋值OrderTotal"""
        data['OrderTotal'] = {"CurrencyCode": "USD", "Amount": 0.00}
        serializer2 = OrderTotalSerializers(data=data['OrderTotal'])
        serializer2.is_valid(raise_exception=True)
        serializer2.save()
        value_id2 = OrdersMoney.objects.all().order_by('-id').first().id
        # 传入order_list数据并存入mysql
        # TODO PaymentMethodDetail
        # serializer3 = PaymentMethodDetailsSerializers(data=data['PaymentMethodDetails'])
        # serializer3.is_valid()
        # serializer3.save()
        # value_id3 = PaymentMethodDDetails.objects.all().order_by('-id').first().id

        now_time = datetime.datetime.now().strftime("%Y%m%D%H%m%S")[12:] + \
                   str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
                   str(random.randint(0, 9)) + str(random.randint(0, 9)) + \
                   str(random.randint(0, 9)) + str(random.randint(0, 9))
        data['MerchantOrderID'] = "TQ" + now_time + "1"
        data['MerchantFulfillmentID'] = "TQ" + now_time + "3"

        data['TQName'] = "TQ" + ''.join(str(uuid.uuid1()).split('-'))[6:20].upper() + ''.join(random.sample(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 5))
        if 'BuyerName' not in data.keys():
            data['BuyerName'] = '暂无'
        # data['MerchantOrderItemID'] = "TQ" + now_time + "2"
        # data['MerchantFulfillmentItemID'] = "TQ" + now_time + "4"

        # data['PaymentMethodDetails'] = value_id3
        # data['OrderItemId'] = OrderItemId
        data['OrderTotal'] = value_id2

        try:
            serializer = UpdateMysqlOrdersSerializers2(data=data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        except Exception as e:

            OrdersMoney.objects.all().order_by('-id').first().delete()
            logger.error(e)
            return
    except Exception as e:

        logger.error(e)
        transaction.savepoint_rollback(save_id)

    order_id = Orders.objects.all().order_by("-id").first().id
    xml_dict = get_order_item(data["AmazonOrderId"], store_id)

    if isinstance(xml_dict['OrderItem'], list):


        for j in xml_dict['OrderItem']:
            j['AmazonOrderId'] = data["AmazonOrderId"]
            if j["QuantityOrdered"] == "0":
                order_item_data_to_mysql1(j, order_id)
            else:
                order_item_data_to_mysql2(j, order_id)
    else:
        xml_dict['OrderItem']['AmazonOrderId'] = data["AmazonOrderId"]
        if xml_dict['OrderItem']["QuantityOrdered"] == '0':
            order_item_data_to_mysql1(xml_dict['OrderItem'], order_id)
        else:
            order_item_data_to_mysql2(xml_dict['OrderItem'], order_id)

    transaction.savepoint_commit(save_id)


class MysqlOfOrderUpdate:


    def update_orders_except_shipped(self,i):
        SellerId = i.seller_id if i.seller_id != '' else ''
        MWSToken = i.mws_token if i.mws_token != '' else ''
        orders = Orders.objects.filter(OrderStatus__in=["Unshipped", "UnDealed"],IsSubmitTrackingNumber=False, FulfillmentChannel='MFN')
        # orders = Orders.objects.all()
        orders = orders.filter(SellerStore=i.id)
        AmazonOrderIdList = [i.AmazonOrderId for i in orders]
        if len(AmazonOrderIdList) == 0:
            return []
        # SellerId = "AXJGQAHIXO0GH"
        # MWSToken = "amzn.mws.1eb6a110-d7ba-3bea-481e-ff3006711b67"
        # AmazonOrderIdList = ["112-4651100-7901811"]
        if len(AmazonOrderIdList) >= 50:

            n = 50
            AmazonOrderIdList_list = [AmazonOrderIdList[i:i + n] for i in range(0, len(AmazonOrderIdList), n)]
            data_list = list()

            for AmazonOrderIdList in AmazonOrderIdList_list:

                time.sleep(60)
                x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=str(SellerId), auth_token=str(MWSToken))
                order_except_shipped = x.get_order(AmazonOrderIdList)
                response_data = order_except_shipped.original
                xml_dict = xmltodict.parse(response_data)

                xml_dict = xml_dict["GetOrderResponse"]["GetOrderResult"]["Orders"]["Order"]
                if isinstance(xml_dict, dict):
                    data_list.append(xml_dict)
                else:
                    data_list += xml_dict

            return data_list
        else:
            x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=str(SellerId), auth_token=str(MWSToken))
            order_except_shipped = x.get_order(AmazonOrderIdList)
            response_data = order_except_shipped.original
            xml_dict = xmltodict.parse(response_data)
            xml_dict = xml_dict["GetOrderResponse"]["GetOrderResult"]["Orders"]["Order"]

            return xml_dict




    def get_user_list(self):
        user_info = User.objects.all()
        username_list = list()
        for i in user_info:
            username_list.append(i.username)

        return username_list

    def get_store_list(self):
        store_info = StoreManagement.objects.all()
        return store_info

    @threads(5)
    def let_mysql_order_update(self, i):

        """
        既然是更新订单就得以 上次更新时间为开始时间   现在时间为结束时间 开始更新   所以得有一个字段记录更新时间
        CreatedAfter = 数据库查询上次的更新时间
        CreateBefore = datetime.datetime.now()

        # """
        # print(f"{i.store}开始更新")
        data_str_list = list()


        # 2 遍历每一组 SellerId MWSAuthToken  发起请求 获取响应数据


        if len(Orders.objects.filter(SellerStore=i.id)) == 0:
            order_update_time = datetime.datetime(2019, 9, 15)
        else:
            # order_update_time = i.order_update_time + datetime.timedelta(hours=8)
            order_update_time = i.order_update_time - datetime.timedelta(hours=1)


        CreatedAfter = iosformat.isoformat(order_update_time)

        data_dict = dict()
        SellerId = i.seller_id if i.seller_id != '' else ''
        MWSToken = i.mws_token if i.mws_token != '' else ''
        # staff_id = i.staff_id
        store_id = i.id
        store_name = i.store
        # staff_name = User.objects.filter(id=staff_id)[0].username
        time.sleep(1)

        x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=str(SellerId), auth_token=str(MWSToken))
        try:
            orders = x.list_orders(created_after=CreatedAfter, marketplaceids=marketplaceids)
        except Exception as e:
            logger.error(str(e))
            return
        now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
        order_update_time = {"order_update_time": now_time}
        serializer = UpdateTimeSerializer(data=order_update_time)
        serializer.is_valid()
        i.order_update_time = serializer.data['order_update_time']
        i.save()
        # 每次一个店铺请求完成 记录时间节点
        orders_number = 0   # 入库订单量记录

        response_data = orders.original
        xml_dict = xmltodict.parse(response_data)
        # staff_info = {'staff_id': staff_id, 'staff_name': staff_name}
        store_info = {'store_name': store_name}

        xml_dict['store_info'] = store_info
        # xml_dict['staff_info'] = staff_info
        next_token = xml_dict["ListOrdersResponse"]["ListOrdersResult"].get("NextToken")

        xml_dict = xml_dict["ListOrdersResponse"]["ListOrdersResult"].get("Orders")


        if xml_dict is not None:
            # time.sleep(5)

            for j, k in xml_dict.items():

                if not isinstance(k, list):
                    k['SellerStore'] = i.id
                    if k["OrderStatus"] == "Pending":
                        if k['FulfillmentChannel'] == 'AFN':
                            data_to_mysql2(k, store_id)
                    elif k["OrderStatus"] == "Canceled":
                            data_to_mysql2(k, store_id)
                    elif k['OrderStatus'] in ['Shipped','Unshipped']:
                        data_to_mysql1(k, store_id)
                    else:
                        pass
                else:
                    for o in k:
                        o['SellerStore'] = i.id
                        if o['OrderStatus'] in ['Shipped','Unshipped']:
                            data_to_mysql1(o, store_id)
                        elif o['OrderStatus'] == "Canceled":
                            data_to_mysql2(o, store_id)
                        elif o['OrderStatus'] == "Pending":
                            if o['FulfillmentChannel'] == 'AFN':
                                data_to_mysql2(o, store_id)
                        else:
                            pass
            if not isinstance(xml_dict["Order"], list):
                data_str = store_name + "同步成功，更新1条订单"
            else:
                orders_number += len(xml_dict["Order"])
                data_str = store_name + "同步成功，更新" + str(orders_number) + "条订单"
            # data_str_list.append(data_str)
        else:
            data_str = store_name + "同步成功，更新0条订单"

        while next_token:
            # print("next_token开始更新")
            next_orders = x.list_orders(next_token=next_token)
            response_data = next_orders.original
            xml_dict = xmltodict.parse(response_data)
            # staff_info = {'staff_id': staff_id, 'staff_name': staff_name}
            store_info = {'store_name': store_name}

            xml_dict['store_info'] = store_info
            # xml_dict['staff_info'] = staff_info
            next_token = xml_dict["ListOrdersByNextTokenResponse"]["ListOrdersByNextTokenResult"].get("NextToken")

            xml_dict = xml_dict["ListOrdersByNextTokenResponse"]["ListOrdersByNextTokenResult"].get("Orders")
            if xml_dict is not None:
                # time.sleep(5)

                for j, k in xml_dict.items():

                    if not isinstance(k, list):
                        k['SellerStore'] = i.id
                        if k["OrderStatus"] == "Pending":
                            if k['FulfillmentChannel'] == 'AFN':
                                data_to_mysql2(k, store_id)
                        elif k["OrderStatus"] == "Canceled":
                            data_to_mysql2(k, store_id)
                        elif k['OrderStatus'] in ['Shipped', 'Unshipped']:
                            data_to_mysql1(k, store_id)
                        else:
                            pass
                    else:
                        for o in k:
                            o['SellerStore'] = i.id
                            if o['OrderStatus'] in ['Shipped', 'Unshipped']:
                                data_to_mysql1(o, store_id)
                            elif o['OrderStatus'] == "Canceled":
                                data_to_mysql2(o, store_id)
                            elif o['OrderStatus'] == "Pending":
                                if o['FulfillmentChannel'] == 'AFN':
                                    data_to_mysql2(o, store_id)
                            else:
                                pass
                if not isinstance(xml_dict["Order"], list):
                    data_str = store_name + "同步成功，更新1条订单"
                else:
                    orders_number += len(xml_dict["Order"])
                    data_str = store_name + "同步成功，更新" + str(orders_number) + "条订单"
                # data_str_list.append(data_str)
            else:
                data_str = store_name + "同步成功，更新0条订单"
            # if not next_token:
            #     print("next_token的更新完毕")


        redis = get_redis_connection('order_update_info')

        redis.rpush(f"new_{store_name}", data_str.encode("GBK"))


        return_data = {
            "store_name": store_name,
            "data_str": data_str
        }


        return return_data
        # update_status = "更新完毕"


class UpdateOrdersExceptShipped(APIView):
    permission_classes = [IsAuthenticated]
    def get(self,request):
        user = request.user
        action = f"{user}更新非发货成功订单"
        task = MysqlOfOrderUpdate()
        store_list = task.get_store_list()
        max_num = len(store_list)

        order_list = list()
        for i in range(0,max_num):
            order = task.update_orders_except_shipped(store_list[i])

            if isinstance(order, dict):
                order_list.append(order)
            else:
                order_list += order
        for j in order_list:
            if j['OrderStatus'] != "Unshipped":
                order_obj = Orders.objects.get(AmazonOrderId=j['AmazonOrderId'])
                order_obj.OrderStatus = j['OrderStatus']
                order_obj.save()


        return Response(order_list)



class OrderItemView(APIView):

    def post(self, request):
        AmazonOrderId = request.POST.get('AmazonOrderId')
        action = f"查看{AmazonOrderId}详情"
        try:
            order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        except Exception as e:
            return Response({"error_msg": str(e)})
        serializer = OrderItemOfOneSerializer(order)

        return Response({"success_msg": serializer.data})


class StandardPageNumberPagination(PageNumberPagination):
    page_size = 30
    page_size_query_description = 'page_size'
    max_page_size = 100


class GetDataForXiaoMi(APIView):
    def get(self, request):
        action = "获取店小秘数据"
        # 和数据库建立连接
        conn = pymysql.connect('localhost', 'vne123', '123', charset='utf8')
        # 创建游标
        cur = conn.cursor()
        # 选择数据库
        cur.execute('use vnemy')
        # 导入数据
        # 1 创建对象
        sfx = ScriptForXiaomi()
        # 2 爬取数据
        response = sfx.get_response_data()
        # 3 数据转换与提取
        data_of_tuple = sfx.counter_data(response)
        # xiaomidata = list(data_of_tuple)
        # 4 将数据存入mysql
        sfx.data_to_mysql(cur, data_of_tuple)
        cur.close()
        conn.commit()
        # 关闭数据库服务器连接，释放内存
        conn.close()

        return Response({'xiaomidata': data_of_tuple})

# TODO
# class OrdersListView(GenericAPIView):
#     """返回订单列表"""
#     queryset = Orders.objects.all()
#     pagination_class = StandardPageNumberPagination
#     serializer_class = OrderListSerializer
#
#     def get(self, request, status):
#         # AmazonOrderId = {"AmazonOrderId":request.GET.get("AmazonOrderId")}
#         # OrderItemId = {"OrderItemId":request.GET.get("OrderItemId")}
#         # TrackingNum = {"TrackingNum":request.GET.get("TrackingNum")}
#         # StoreName = {"StoreName":request.GET.get("StoreName")}
#         # BuyerName = {"BuyerName":request.GET.get("BuyerName")}
#         # SellerSKU = {"SellerSKU":request.GET.get("SellerSKU")}
#         # data_list_info = [AmazonOrderId,OrderItemId,TrackingNum,StoreName,BuyerName,SellerSKU]
#         # key="123"
#         # value = "123"
#
#         # action = request.GET.get("action")
#         # if action != None:
#         #     search_info = json.loads(action)

#
#         OrderStatus = status

#         if OrderStatus != "all":
#             orders = Orders.objects.filter(OrderStatus=OrderStatus)
#         else:
#             orders = Orders.objects.all()
#
#         # orders = orders.filter(**search_info)
#         page = self.paginate_queryset(orders)
#         if page is not None:
#             serializer = self.get_serializer(page, many=True)
#
#             page_data = self.get_paginated_response(serializer.data).data
#
#         for order in page_data['results']:
#
#             AmazonOrderId = order['AmazonOrderId']
#             OrderItems = OrderItem.objects.filter(AmazonOrderId=AmazonOrderId)
#             CustomsDec_list = list()
#             Title_list = list()
#             GoodsImage_list = list()
#             ASIN_list = list()
#             SellerSKU_list = list()
#             ConditionId_list = list()
#             OrderItemId_list = list()
#             QuantityShipped_list = list()
#             ItemPrice_list = list()
#             ShippingPrice_list = list()
#
#
#             j = 0
#             for i in OrderItems:
#                 j += 1
#                 serializer_item = OrderItemDictOfOneSerializer(i)

#                 # if serializer_item.data['CustomsDeclarationInfo'] == None:
#                 #     serializer_item.data['CustomsDeclarationInfo'] = dict()

#                 #           type(serializer_item.data['CustomsDeclarationInfo']))
#                 #
#                 #     serializer_item.data['CustomsDeclarationInfo']['id'] = "填写报关信息"
#                 # else:
#                 #     serializer_item.data['CustomsDeclarationInfo']['id'] = "报关已填"
#                 CustomsDec_list.append(serializer_item.data['CustomsDeclarationInfo'])
#                 GoodsImage_list.append(serializer_item.data['GoodsImage'])
#                 Title_list.append(serializer_item.data['Title'])
#                 ASIN_list.append(serializer_item.data['ASIN'])
#                 SellerSKU_list.append(serializer_item.data['SellerSKU'])
#                 ConditionId_list.append(serializer_item.data['ConditionId'])
#                 OrderItemId_list.append(serializer_item.data['OrderItemId'])
#                 QuantityShipped_list.append(serializer_item.data['QuantityShipped'])
#                 ItemPrice_list.append(serializer_item.data['ItemPrice'])
#                 ShippingPrice_list.append(serializer_item.data['ShippingPrice'])
#             order['OrderItem'] = dict()
#             order['OrderItem']['GoodsImage'] = GoodsImage_list
#             order['OrderItem']['Title'] = Title_list
#             order['OrderItem']['ASIN'] = ASIN_list
#             order['OrderItem']['SellerSKU'] = SellerSKU_list
#             order['OrderItem']['ConditionId'] = ConditionId_list
#             order['OrderItem']['OrderItemId'] = OrderItemId_list
#             order['OrderItem']['QuantityShipped'] = QuantityShipped_list
#             order['OrderItem']['ItemPrice'] = ItemPrice_list
#             order['OrderItem']['ShippingPrice'] = ShippingPrice_list
#             order['OrderItem']['CustomsDec'] = CustomsDec_list
#
#
#         return Response({"success_msg": page_data})


# {'用户id':'',
# "平台mall":'',
# "店铺store":'',
#  '状态status':'',
#  '国家countrycode':'',
# '物流方式shippingmethod':'',
#  '排序方式sortby':'',
# '搜索信息':'搜索方式_输入内容'}
# }

class OrdersListPageNumberPagination(PageNumberPagination):
    page_size = 30 # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'  # URL中页码的参数
    max_page_size = None  # 最大页码数限制

class OrdersListView(APIView):
    # permission_classes = [IsAuthenticated]
    """订单列表"""
    def get(self,request):

        parms = request.query_params  # 获取查询参数
        id = parms.get('id')  # 获取用户ID
        user = User.objects.get(id = id)  # 获取用户
        mall = parms.get('mall')  # 获取平台
        mall = mall if mall else 'amazon'  # 默认不传选择amzon
        if mall == 'amazon':
            store = parms.get('store')  # 获取店铺
            if store=='all':
                try:
                    user_store = UserAndStore.objects.filter(staff=user.id)
                    stores = [i.store for i in user_store]
                    # stores = user.storemanagement_set.all()  # 获取所有店铺
                except Exception as e:
                    return Response({'error_msg': str(e)})

                store_id_list = [store.id for store in stores] # 获取店铺id列表
                try:
                    queryset = Orders.objects.filter(SellerStore__in=store_id_list)
                except Exception as e:
                    return Response({'error_msg': str(e)})
            else:
                try:
                    queryset = Orders.objects.filter(SellerStore__store=store)
                except Exception as e:
                    return Response({'error_msg': str(e)})
            time = parms.get("time")
            if time:

                time = re.split(r'_', time, 1)
                time_type = time[0]
                time_range = time[1]

                time_range = time_range.split(",")

                time_range[0] = iosformat.isoformat(datetime.datetime.strptime(time_range[0], '%Y/%m/%d'))
                time_range[1] = iosformat.isoformat(datetime.datetime.strptime(time_range[1], '%Y/%m/%d') + datetime.timedelta(days=1))

                if time_type == "PurchaseDate":
                    try:
                        queryset = queryset.filter(PurchaseDate__range=(time_range[0], time_range[1]))
                    except Exception as e:
                        return Response({'error_msg': str(e)}, status=status.HTTP_400_BAD_REQUEST)
                elif time_type == "LatestShipDate":
                    try:
                        queryset = queryset.filter(LatestShipDate__range=(time_range[0], time_range[1]))
                    except Exception as e:
                        return Response({'error_msg': str(e)}, status=status.HTTP_400_BAD_REQUEST)

            order_status = parms.get('status') #获取订单状态
            # 记录系统日志
            # operation_log_time = datetime.datetime.now()
            # operation_log_user = request.user.username
            # action = f"{operation_log_user}------查看了{status}订单列表------{operation_log_time}"
            # redis = get_redis_connection('order_update_info')
            # redis.rpush("operation_log", f'{action}'.encode("GBK"))

            if order_status!='all':
                try:
                    queryset = queryset.filter(OrderStatus=order_status)
                except Exception as e:
                    return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
            countrycode= parms.get('countrycode')  # 获取国家区域
            if countrycode!='all':
                try:
                    queryset = queryset.filter(ShippingAddress__CountryCode=countrycode)
                except Exception as e:
                    return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)

            # shippingmethod = parms.get('shippingmethod')  # 获取物流方式
            # if shippingmethod:
            #     queryset = queryset.filter(shippingmethod=shippingmethod)
            # filtertype = parms.get('filtertype')  # 获取筛选类型
            # if filtertype == '未填写报关信息':
            #     pass
            # if filtertype == '选择物流方式':
            #     pass
            sortby = parms.get('sortby')  # 获取排序方式
            if sortby:
                try:
                    queryset = queryset.order_by(sortby)
                except Exception as e:
                    return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
            search = parms.get('search')  # 获取搜索参数
            if search:
                search= re.split(r'_',search,1)
                search_type = search[0] # 搜索参数类型
                search_content = search[1] # 搜索参数
                # search_content_list = search_content.replace(',', ' ').replace('，', ' ').split(' ')
                # search_content_list = [i for i in search_content_list if i]

                if search_type == 'AmazonOrderId':  # 通过订单号
                    try:
                        queryset = queryset.filter(AmazonOrderId__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'OrderItemId':  # 通过包裹号
                    try:
                        queryset = queryset.filter(orderitem__OrderItemId__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'TQName':  # 通过包裹号
                    try:
                        queryset = queryset.filter(TQName__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'TrackingNumber':  # 通过物流跟踪号
                    try:
                        queryset = queryset.filter(TrackingNumber__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'WayBillNumber':  # 通过物流运单号
                    try:
                        queryset = queryset.filter(WayBillNumber__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'SellerSKU':  # 通过商品的卖家SKU
                    try:
                        queryset = queryset.filter(orderitem__SellerSKU__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'ASIN':  # 通过商品编码ASIN
                    try:
                        queryset = queryset.filter(orderitem__ASIN__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'BuyerName':  # 通过买家姓名
                    try:
                        queryset = queryset.filter(BuyerName__contains=search_content)
                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
                elif search_type == 'Name':  # 通过买家姓名

                    try:
                        queryset = queryset.filter(ShippingAddress__Name__contains=search_content)

                    except Exception as e:
                        return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)

        page_obj = OrdersListPageNumberPagination()
        page_article = page_obj.paginate_queryset(queryset=queryset, request=request, view=self)
        serializer = OrderListSerializer(page_article, many=True)
        response = page_obj.get_paginated_response(serializer.data)

        return response



class OrderItemsListView(ListAPIView):
    serializer_class = OrderItemListSerializer
    queryset = OrderItem.objects.all()
    pagination_class = StandardPageNumberPagination


class GetOrder(APIView):
    def post(self, request):
        AmazonOrderId = request.POST.get('AmazonOrderId')
        action = f"查看{AmazonOrderId}订单"
        if AmazonOrderId is None:
            return Response({'error_msg': '请输入AmazonOrderId'})
        if not isinstance(AmazonOrderId, str):
            return Response({'error_msg': '您输入AmazonOrderId类型有误'})
        try:
            order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        except Exception as e:
            return Response({'error_msg': str(e)})
        serializer = OrderListSerializer(order)
        return Response({"success_msg": serializer.data})



class UpdateMysqlOrders(APIView):

    def get(self, request):
        # 1 获取所有SellerId MWSAuthToken

        # 既然是更新订单就得覆盖原订单列表  首先删除原订单 再做新的查询入库工作            错误思想

        # Orders.objects.all().delete()
        # Address.objects.all().delete()
        # PaymentMethodDDetails.objects.all().delete()
        # OrdersMoney.objects.all().delete()
        #
        # OrderItem.objects.all().delete()
        # TaxCollection.objects.all().delete()
        # ProductInfos.objects.all().delete()
        # OrdersItemMoney.objects.all().delete()

        """
        既然是更新订单就得以 上次更新时间为开始时间   现在时间为结束时间 开始更新   所以得有一个字段记录更新时间
        CreatedAfter = 数据库查询上次的更新时间
        CreateBefore = datetime.datetime.now()

        # """
        global update_list
        global update_status
        global percent

        update_list = []
        percent = 0
        update_status = '更新中...'
        # if len(Orders.objects.all()) == 0:
        #     order_update_time = datetime.datetime(2019, 1, 1)
        # else:
        #     order_update_time = UpdateTime.objects.all().last().order_update_time
        #
        # CreatedAfter = isoformat(order_update_time)


        data_str_list = list()

        # store_info = StoreManagement.objects.all()
        store_info = StoreManagement.objects.filter(total_flow=1)
        p = 0
        amount = len(store_info)
        # 2 遍历每一组 SellerId MWSAuthToken  发起请求 获取响应数据
        for i in store_info:
            # time.sleep(6)
            p += 1
            if len(Orders.objects.filter(SellerStore=i.id)) == 0:
                order_update_time = datetime.datetime(2019, 7, 20)
            else:
                order_update_time = i.order_update_time - datetime.timedelta(minutes=3)

            CreatedAfter = iosformat.isoformat(order_update_time)

            data_dict = dict()
            SellerId = i.seller_id if i.seller_id != '' else ''
            MWSToken = i.mws_token if i.mws_token != '' else ''
            staff_id = i.staff_id
            store_id = i.id
            store_name = i.store
            # staff_name = User.objects.filter(id=staff_id)[0].username
            time.sleep(1)


            x = mws.Orders(access_key=access_key, secret_key=secret_key, account_id=str(SellerId), auth_token=str(MWSToken))
            try:
                orders = x.list_orders(created_after=CreatedAfter, marketplaceids=marketplaceids)
            except Exception as e:
                return Response({"error_msg": str(e)})

            response_data = orders.original
            xml_dict = xmltodict.parse(response_data)
            # staff_info = {'staff_id': staff_id, 'staff_name': staff_name}
            store_info = {'store_name': store_name}
            xml_dict['store_info'] = store_info
            # xml_dict['staff_info'] = staff_info
            xml_dict = xml_dict["ListOrdersResponse"]["ListOrdersResult"]['Orders']

            if xml_dict is not None:
                # time.sleep(5)

                for j, k in xml_dict.items():

                    if not isinstance(k, list):
                        if k["OrderStatus"] == "Canceled":
                            k['SellerStore'] = i.id
                            data_to_mysql2(k, store_id)
                        elif k['OrderStatus'] == 'Unshipped':
                            data_to_mysql1(k, store_id)
                        elif k['OrderStatus'] == 'Shipped':
                            data_to_mysql2(k, store_id)
                        else:
                            pass
                    else:
                        for o in k:


                            o['SellerStore'] = i.id
                            if o['OrderStatus'] == 'Shipped':
                                data_to_mysql1(o, store_id)
                            elif o['OrderStatus'] == 'Unshipped':

                                data_to_mysql1(o, store_id)
                            elif o['OrderStatus'] == 'Canceled':
                                data_to_mysql2(o, store_id)
                            else:
                                pass
                if not isinstance(xml_dict["Order"], list):
                    data_str = store_name + "同步成功，更新1条订单"
                else:
                    data_str = store_name + "同步成功，更新" + str(len(xml_dict["Order"])) + "条订单"
                data_str_list.append(data_str)
                update_list = data_str_list

            else:
                data_str = store_name + "同步成功，更新0条订单"
                data_str_list.append(data_str)

                update_list = data_str_list


            now_time = (datetime.datetime.now() - datetime.timedelta(minutes=2)).strftime("%Y-%m-%d %H:%M")
            order_update_time = {"order_update_time": now_time}
            serializer = UpdateTimeSerializer(data=order_update_time)
            serializer.is_valid()
            i.order_update_time = serializer.data['order_update_time']
            i.save()
            if amount == 0:
                return Response({"error_msg": "店铺数量为零"})
            percent = round(p/amount, 2)*100
            # percent = "{}%".format(percent)


        update_status = "更新完毕"

        # 4 由响应数据组成订单列表返回给前端展示
        return Response({"success_msg": "更新成功"})


class GetUpdateList(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------同步订单------{operation_log_time}"

        user = request.user
        redis = get_redis_connection('order_update_info')
        # user_store = StoreManagement.objects.filter(staff=user.id)
        user_store = UserAndStore.objects.filter(staff=user.id)
        user_store = [i.store for i in user_store]
        new_result = list()
        for store in user_store:

            result = redis.lrange(f'old_{store.store}', 0, -1)

            new_result.append(result[0].decode("GBK"))
        redis.rpush("operation_log", f'{action}'.encode("GBK"))
        return Response({"success_msg": new_result},status=status.HTTP_200_OK)

class GetOperationLog(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):

        redis = get_redis_connection('order_update_info')
        result = redis.lrange('operation_log', 0, -1)
        new_result = [i.decode("GBK") for i in result]

        return Response({"success_msg": new_result[::-1]})


class GoodsSellCompetition(APIView):
    """返回商品排名列表"""
    # pagination_class = StandardPageNumberPagination
    # queryset = GoodsRank.objects.all()
    # serializer_class = GoodsRankSerializer
    permission_classes = [IsAuthenticated]
    def get(self, request):
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------获取商品排名列表------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        GoodsRank.objects.all().delete()
        order_items = OrderItem.objects.exclude(QuantityShipped=0)
        serializer_goods = GoodsItemSerializer(order_items,many=True)
        data_dict_list = list()
        data_dict = dict()
        for i in serializer_goods.data:
            data_dict['Image'] = i['GoodsImage']
            data_dict['title'] = i['Title']
            data_dict['StoreName'] = i['Order']['SellerStore']['store']
            data_dict['SellerSKU'] = i['SellerSKU']
            data_dict['ASIN'] = i['ASIN']
            data_dict['Time'] = i['Order']['PurchaseDate']
            data_dict['sell_numb'] = i['QuantityShipped']
            data_dict['goods_price'] = i['ItemPrice']['Amount']
            data_dict['SalesChannel'] = i['Order']['SalesChannel']
            create_goods_rank_serialzier = GoodsRankSerializer(data=data_dict)
            create_goods_rank_serialzier.is_valid(raise_exception=True)
            create_goods_rank_serialzier.save()
        # data_dict_list.append(data_dict)
        return Response("ok")
        # asin_dict = dict()
        # for i in order_items:
        #     if asin_dict.get(i.ASIN):
        #         asin_dict[i.ASIN] += int(i.QuantityShipped)
        #     else:
        #         asin_dict[i.ASIN] = int(i.QuantityShipped)

        # asin_dict_list = list()
        # for k, v in asin_dict.items():
        #     obj = OrderItem.objects.filter(Q(ASIN=k) & Q(ItemPrice__isnull=False)).first()
        #     new_dict = dict()
        #     new_dict['ASIN'] = k
        #     new_dict['sell_numb'] = v
        #     new_dict['title'] = obj.Title
        #     new_dict['Image'] = obj.GoodsImage
        #     new_dict['SellerSKU'] = obj.SellerSKU
        #
        #     price_serializer = OrderItemListSerializer(obj)
        #     # price_serializer.is_valid(raise_exception=True)

        #     a = float(price_serializer.data['ItemPrice']['Amount'])
        #     b = float(price_serializer.data['QuantityShipped'])
        #     if b == 0:
        #         new_dict['unit_price'] = ('%.2f' % a)
        #     else:
        #         new_dict['unit_price'] = ('%.2f' % (a / b))
        #     new_dict['amount_price'] = ("%.2f" % (float(new_dict['unit_price']) * new_dict['sell_numb']))
        #     new_dict['StoreName'] = price_serializer.data['Order']['SellerStore']['store']
        #
        #     asin_dict_list.append(new_dict)
        #
        # asin_dict_list.sort(key=lambda z: z['sell_numb'])
        # asin_dict_list.reverse()
        # for one_dict in asin_dict_list:
        #     create_goods_range_serializer = GoodsRankSerializer(data=one_dict)
        #     create_goods_range_serializer.is_valid(raise_exception=True)
        #     create_goods_range_serializer.save()
        # return Response("ok")
    def post(self,request):
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------根据筛选条件获取商品排名------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))
        datas = request.data

        SalesChannel = datas.get('SalesChannel')
        StoreName = datas.get('StoreName')
        time_range = datas.get('time_range')
        search = datas.get('search')
        if isinstance(time_range,list):
            return_time = datetime.datetime.strptime(time_range[1], '%Y/%m/%d') - datetime.datetime.strptime(time_range[0],
                                                                                                         '%Y/%m/%d')
            return_time = str(return_time.days)
        else:
            return_time = time_range

        now_time = datetime.datetime.now()

        # seven_time = iosformat.isoformat()
        if isinstance(time_range, list):

            time_range[0] = datetime.datetime.strptime(time_range[0], '%Y/%m/%d')
            time_range[1] = datetime.datetime.strptime(time_range[1], '%Y/%m/%d')
        elif time_range == '7':
            time_range = iosformat.week_get(now_time)
        elif time_range == '30':
            time_range = iosformat.month_get(now_time)
        elif time_range == "all":
            time_range = iosformat.month_get(now_time)
        elif time_range == '1':
            time_range = iosformat.day_get(now_time)
        else:
            time_range = iosformat.month_get(now_time)
        finance_of_goods = GoodsRank.objects.filter(Time__range=(time_range[0], time_range[1]))
        finance_of_goods = finance_of_goods.filter(StoreName__in=StoreName)
        finance_of_goods = finance_of_goods.filter(SalesChannel__in=SalesChannel)

        if search:

            if search.get('method') == "ASIN":
                finance_of_goods = finance_of_goods.filter(ASIN__contains=search.get('content'))
            elif search.get('method') == "SKU":
                finance_of_goods = finance_of_goods.filter(SKU__contains=search.get('content'))
        # finance_of_goods = finance_of_goods.filter(FulfillmentChannel__in=deliver_method)
        serializer = GoodsRankSerializer(finance_of_goods, many=True)


        finance_dict_list = list()
        finance_dict = dict()
        for i in serializer.data:

            if finance_dict.get(i["ASIN"]) == None:
                finance_dict_list.append(i)
                finance_dict[i.get("ASIN")] = 1
            else:
                finance_dict[i.get("ASIN")] += 1
        new_finance_dict_list = list()
        Sell_num_sum = 0
        goods_amount_price_sum = 0
        for obj in finance_dict_list:
            new_finance_dict = dict()

            new_finance_dict["Image"] = obj['Image']
            new_finance_dict["title"] = obj['title']
            new_finance_dict["StoreName"] = obj['StoreName']
            new_finance_dict["SellerSKU"] = obj['SellerSKU']
            new_finance_dict["ASIN"] = obj['ASIN']
            new_finance_dict["SellNum"] = finance_dict[obj['ASIN']]
            Sell_num_sum += new_finance_dict["SellNum"]
            new_finance_dict["goods_amount_price"] = float(obj['goods_price']) * int(finance_dict[obj['ASIN']])
            goods_amount_price_sum += new_finance_dict["goods_amount_price"]
            new_finance_dict["SalesChannel"] = obj['SalesChannel']
            new_finance_dict_list.append(new_finance_dict)

        new_finance_dict_list.sort(key=lambda z: z['SellNum'], reverse=True)


        sum_list = {"SKU_num_sum":len(new_finance_dict_list), "Sell_num_sum":Sell_num_sum, "goods_amount_price_sum":round(goods_amount_price_sum,2)}
        resp_data = {"goods_finance":new_finance_dict_list,"sum_list":sum_list}
        return Response(resp_data)



class GetImage(APIView):

    def post(self,request):
        datas = request.data
        time_range = datas.get('time')

        # time_start = [int(i) for i in time[0].split("/")]
        # time_end = [int(j) for j in time[1].split("/")]
        time_range[0] = iosformat.isoformat(datetime.datetime.strptime(time_range[0], '%Y/%m/%d'))
        time_range[1] = iosformat.isoformat(datetime.datetime.strptime(time_range[1], '%Y/%m/%d'))



        return Response("OK")

    def get(self, request):



        # file_path = os.path.join(BASE_DIR, 'apps/orders/image_need_file/proxy_list')
        # #新建一个img文件夹来保存图片
        # # if os.path.exists('./img'):
        # #     pass
        # # else:
        # #     os.mkdir('./img')
        # img_method = ImageMethod()
        # img_method.save_start()
        # img_method.ip_run()
        #
        # order_items = OrderItem.objects.all()
        # ASIN_list = list()
        # with open(file_path, "r", encoding='utf-8') as f:
        #     lines = f.readlines()
        #     for line in lines:
        #         IP_PROXY_LIST.append(line.strip())
        # for order_item in order_items:
        #     ASIN = order_item.ASIN
        #     ASIN_list.append(ASIN)
        #
        #     url = f'https://www.amazon.com/gp/product/{ASIN}'
        #     headers = {'User-Agent': random.choice(USER_AGENT_LIST)}
        #     proxies = {'ip_proxy': random.choice(IP_PROXY_LIST)}
        #     res = requests.get(url,proxies=proxies,headers=headers)
        #
        #     content = etree.HTML(res.text)
        #
        #     img = content.xpath("//div[@id = 'imgTagWrapperId']/img/@src")
        #     # if img:


        # i = 0
        # for img in imgs:

        #
        #
            #自定义图片名称
            # urllib.request.urlretrieve(str(img), filename='mypic{}.png'.format(i))
            # img = urllib.request.urlopen(img).read()

        # fdfs_storage = FasfDFSStorage()
        # file_name = fdfs_storage.save('mypic{}.png'.format(i), img)

        #
            # i += 1

        return Response({'success_msg':"ok"})

class UpdateInfo(APIView):
    permission_classes = [IsAuthenticated]
    def post(self, request):
        """修改订单备注
        {
        "Order"
        'username':""xiaobai,
         'Info':已拣货
         },
        """
        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------修改或添加订单备注------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        data = request.data

        if data.get('id') is not None:   # 传过来的数据有id 就进行修改
            try:
                info = Infos.objects.get(id=data['id'])
            except Exception as e:
                return Response({"error_msg": str(e)})
            info_serializer = OrderInfoSerializer(info, data=data)
            info_serializer.is_valid()
            info_serializer.save()
            return Response({"success_msg": "修改备注成功"})
        else:   # 没有就新建
            info_serializer = OrderInfoSerializer(data=data)
            info_serializer.is_valid()
            info_serializer.save()


            return Response({"success_msg": "备注成功"})

    def get(self, request):
        """删除订单备注"""
        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------删除订单备注------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        params = request.query_params
        id = params.get("id")
        if id:
            Infos.objects.get(id=id).delete()
        else:
            return Response({"error_msg":"参数有误"}, status=status.HTTP_404_NOT_FOUND)
        return Response({"success_msg":"删除备注成功"}, status=status.HTTP_200_OK)



class UpdateOrderStatus(APIView):
    """修改订单状态"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """
        :param request:
            AmazonOrderId
            OrderStatus
        :return: success_msg   "修改成功"  error_msg: "修改失败"
        """
        datas = request.data

        data_status = datas['OrderStatus']
        data_dict = dict()
        return_msg = ""

        for AmazonOrderId in datas['AmazonOrderId']:

            data_dict['AmazonOrderId'] = AmazonOrderId
            data_dict['OrderStatus'] = data_status

            serializer = OrderStatuAndTrackingSeiralizer(data=data_dict)
            serializer.is_valid()


            OrderStatus = data_status  # 此时接收的参数为动作参数  Shipped为去发货
            try:

                order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
            except Exception as e:

                return Response({'error_msg': str(e)},status=status.HTTP_400_BAD_REQUEST)
            if OrderStatus == "UnDealed":
                return_msg = "移入待处理成功"
                order.Examine = True
                order.Deal = False
                order.Shipped = False
                status_return = "待处理"

                # Examine_Serializer = ExamineSerializer(data={"Examine": data_dict.get('Examine')})
                # order.Examine = Examine_Serializer.data['Examine']
            elif OrderStatus == "UnBilledTrue":    # 有货
                if order.ApplicationOrderNumber == False:
                    return Response({"error_msg": "未申请运单号"},status=status.HTTP_400_BAD_REQUEST)
                return_msg = "移入待打单成功(有货)"
                order.Examine = True
                order.Deal = True
                order.Shipped = False
                status_return = "有货"

            elif OrderStatus == "UnBilledFalse":    # 缺货
                if order.ApplicationOrderNumber == False:
                    return Response({"error_msg": "未申请运单号"},status=status.HTTP_400_BAD_REQUEST)
                return_msg = "移入待打单成功（缺货）"
                order.Examine = True
                order.Deal = True
                order.Shipped = False
                status_return = "缺货"
                # Deal_Serializer = DealSerializer(data={"Deal": data_dict.get('Deal')})
                # order.Deal = Deal_Serializer.data['Deal']
            elif OrderStatus == 'Shipped':      # 发货成功
                return_msg = '发货成功'
                order.Examine = True
                order.Deal = True
                order.Shipped = True
                status_return = "发货成功"

            elif OrderStatus == 'ShippedField':   # 发货失败
                return_msg = '移入发货失败'
                order.Examine = True
                order.Deal = True
                order.Shipped = False
                status_return = "发货失败"


            elif OrderStatus == 'ShippedWait':   # 发货中
                return_msg = '移入发货中'

                order.Examine = True
                order.Deal = True
                order.Shipped = False
                status_return = "发货中"
                # Shipped_Serializer = ShippedSerializer(data={"Shipped": data_dict.get('Shipped')})
                # order.Shipped = Shipped_Serializer.data['Shipped']

            elif OrderStatus == 'Unshipped':
                return_msg = '移入待审核'
                order.Deal = False
                order.Examine = False
                order.Shipped = False
                status_return = "待审核"
                # Examine_Serializer = ExamineSerializer.data.get['Examine']
            elif OrderStatus == 'LayAside':
                return_msg = '移入搁置'
                status_return = "搁置"

                # Examine_Serializer = ExamineSerializer.data.get['Examine']
            else:
                return Response({"error_msg": "传入状态有误，请检查"},status=status.HTTP_400_BAD_REQUEST)

            #  一个订单有多个包裹时   只有一个运单号
            order.OrderStatus = serializer.data["OrderStatus"]
            order.save()


        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------修改{datas['AmazonOrderId']}订单状态为{status_return}------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))
        return Response({"success_msg": return_msg})

        # return Response("ok")

"""
报关信息分析
1 根据商品ASIN 获取报关信息列表  有就返回 没有就返回none
2 填写报关信息，已存在的报关信息进行报关信息修改
"""


class GetCustomsDeclarationInfoList(APIView):
    permission_classes = [IsAuthenticated]
    """获取报关信息列表"""
    def post(self, request):

        order_item_list = request.data

        data_list = list()
        for order_item_id in order_item_list:
            try:
                order_items = OrderItem.objects.get(OrderItemId=order_item_id)
            except Exception as e:
                return Response({"error_msg": str(e)}, status=status.HTTP_400_BAD_REQUEST)
            serializer = OrderItemForCustomsDeclarationInfosSerializer(order_items)
            data_list.append(serializer.data)

        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------查看{order_item_list}报关信息------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))
        return Response({"success_msg": data_list})


class WriteCustomsDeclarationInfos(APIView):
    permission_classes = [IsAuthenticated]
    """填写报关信息"""
    def post(self, request):
        custom_declaration_list = request.data
        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        order_item__id_list = list()
        if len(custom_declaration_list) == 0:
            return Response({'error_msg': "缺少数据"}, status=status.HTTP_400_BAD_REQUEST)
        for i in custom_declaration_list:

            if i["OrderItemId"] == '':
                return Response({"error_msg":"缺少OrderItemId值"}, status=status.HTTP_400_BAD_REQUEST)
            OrderItemId = i['OrderItemId']

            try:
                order_item = OrderItem.objects.get(OrderItemId=OrderItemId)
            except Exception as e:
                return Response({"error_msg": str(e)}, status=status.HTTP_400_BAD_REQUEST)
            order_item__id_list.append(OrderItemId)
            if i.get("ChineseCustomsDeclaration") == None:
                return Response({"error_msg": "缺少字段"}, status=status.HTTP_400_BAD_REQUEST)
            if i.get("EnglishCustomsDeclaration") == None:
                return Response({"error_msg": "缺少字段"}, status=status.HTTP_400_BAD_REQUEST)
            if i.get("Weight") == None:
                return Response({"error_msg": "缺少字段"}, status=status.HTTP_400_BAD_REQUEST)
            if i.get("Price") == None:
                return Response({"error_msg": "缺少字段"}, status=status.HTTP_400_BAD_REQUEST)
            #查询该条数据CustomsDeclarationInfo是否为None 如果为None则新增CustomsDeclarationInfo 如果有数据则修改数据

            if order_item.CustomsDeclarationInfo is None:

                serializer_of_CustomsDec = CustomsDeclarationInfosSerializer(data=i)
                if i['CustomsCode'] == '':
                    i['CustomsCode'] = '非必填'

                serializer_of_CustomsDec.is_valid()

                serializer_of_CustomsDec.save()
                object1 = CustomsDeclarationInfos.objects.all().order_by('-id').first()

                order_item.CustomsDeclarationInfo = object1
                order_item.save()

            else:

                serializer_of_CustomsDec1 = OrderItemIdSerializer(order_item)
                i["id"]=serializer_of_CustomsDec1.data['CustomsDeclarationInfo']
                if i['CustomsCode'] == '':
                    i['CustomsCode'] = '非必填'

                CustomsDecInfo = CustomsDeclarationInfos.objects.get(id=i['id'])

                serializer_of_CustomsDec2 = CustomsDeclarationAddIdInfosSerializer(data=i)
                serializer_of_CustomsDec2.is_valid()
                CustomsDecInfo.ChineseCustomsDeclaration = serializer_of_CustomsDec2.data['ChineseCustomsDeclaration']
                CustomsDecInfo.EnglishCustomsDeclaration = serializer_of_CustomsDec2.data['EnglishCustomsDeclaration']
                CustomsDecInfo.Weight = serializer_of_CustomsDec2.data['Weight']
                CustomsDecInfo.Price = serializer_of_CustomsDec2.data['Price']
                CustomsDecInfo.CustomsCode = serializer_of_CustomsDec2.data['CustomsCode']
                CustomsDecInfo.IsElectric = serializer_of_CustomsDec2.data['IsElectric']
                CustomsDecInfo.save()

        action = f"{operation_log_user}------填写{order_item__id_list}的报关信息------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        return Response({"success_msg": "ok"})


class OrderDeliver(GenericAPIView):
    """发货按钮"""
    permission_classes = [IsAuthenticated]
    def post(self, request):

        """
        初期构思：
        员工输入订单号，并修改订单状态， 后端修改订单状态  并向亚马逊发送订单报告 告知亚马逊已发货 从而修改亚马逊订单数据

        1 获得订单号 查询数据库该订单数据
        2 根据action 修改订单状态 保存订单状态
        3 向亚马逊发送报告
        4 回传报告 是否上传成功


        中期构思：
        员工输入订单号，修改订单状态， 后端跟踪订单号，查询运单号是否存在于物流官网 之后再上传亚马逊订单报告

        后期构思：
        对接物流，  员工直接操作该订单指定物流公司发货， 获取物流公司该订单运单号，  上传亚马逊订单报告
        :return:
        """

        datas = request.data
        AmazonOrderId = datas.get('AmazonOrderId')
        StatusCode = datas.get('StatusCode')
        OrderStatus = datas.get('OrderStatus')

        deliver_goods_obj = DeliverGoods()
        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------对{AmazonOrderId}虚拟发货------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))
        # 测试

        if AmazonOrderId is None or OrderStatus is None or StatusCode is None:
            return Response({"error_msg":"缺少数据"},status=status.HTTP_400_BAD_REQUEST)
        else:
            if OrderStatus == "UnBilledFalse":
                order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
                if order.ApplicationOrderNumber == False:
                    return Response({"error_msg":"未申请运单"}, status=status.HTTP_400_BAD_REQUEST)

                if order.IsSubmitTrackingNumber == True:
                    return Response({"error_msg":"该订单已向平台提交单号"}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    time.sleep(10)
                    deliver_goods_obj.change_SubmitTrackingNumber(AmazonOrderId)
                    return Response({"success_msg":"虚拟发货成功"},status=status.HTTP_200_OK)
            elif OrderStatus == "Shipped":

                order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
                if order.ApplicationOrderNumber == False:
                    return Response({"error_msg":"未申请运单"}, status=status.HTTP_400_BAD_REQUEST)
                OrderStatus = "ShippedWait"
                deliver_goods_obj.change_order_status(AmazonOrderId,OrderStatus)
                time.sleep(10)
                # 测试省略一步向平台提交运单号
                OrderStatus = "Shipped"
                deliver_goods_obj.change_SubmitTrackingNumber(AmazonOrderId)
                deliver_goods_obj.change_order_status(AmazonOrderId,OrderStatus)
                return Response({"success_msg": "发货成功"}, status=status.HTTP_200_OK)
            else:
                return Response({"error_msg":"参数错误"},status=status.HTTP_400_BAD_REQUEST)

        # # 实战
        # if AmazonOrderId is None or OrderStatus is None or StatusCode is None:
        #     return Response({"error_msg":"缺少数据"},status=status.HTTP_400_BAD_REQUEST)
        # else:
        #     if OrderStatus == "UnBilledFalse":
        #         order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        #         if order.ApplicationOrderNumber == False:
        #             return Response({"error_msg":"未申请运单"}, status=status.HTTP_400_BAD_REQUEST)
        #
        #         if order.IsSubmitTrackingNumber == True:
        #             return Response({"error_msg":"该订单已向平台提交单号"}, status=status.HTTP_400_BAD_REQUEST)
        #         else:
        #             time.sleep(10)
        #             msg1 = deliver_goods_obj.order_acknowledgment(AmazonOrderId, StatusCode)
        #             if msg1['MessagesProcessed'] == msg1['MessagesSuccessful']:
        #
        #                 msg2 = deliver_goods_obj.order_fulfillment(AmazonOrderId)
        #                 if msg2['MessagesProcessed'] == msg2['MessagesSuccessful']:
        #                     deliver_goods_obj.change_SubmitTrackingNumber(AmazonOrderId)
        #                     return Response({"success_msg":"虚拟发货成功"},status=status.HTTP_200_OK)
        #                 else:
        #                     return Response({"error_msg": "虚拟发货失败"}, status=status.HTTP_400_BAD_REQUEST)
        #             else:
        #                 return Response({"error_msg": "虚拟发货失败"}, status=status.HTTP_400_BAD_REQUEST)
        #     elif OrderStatus == "Shipped":
        #         order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        #         if order.ApplicationOrderNumber == False:
        #             return Response({"error_msg": "未申请运单"}, status=status.HTTP_400_BAD_REQUEST)
        #         else:
        #             # 发货按钮    第一步转移订单到发货中
        #             OrderStatus = "ShippedWait"
        #             deliver_goods_obj.change_order_status(AmazonOrderId,OrderStatus)
        #             #  第二步  同步运单号到亚马逊后台
        #             msg1 = deliver_goods_obj.order_acknowledgment(AmazonOrderId, StatusCode)
        #             if msg1['MessagesProcessed'] == msg1['MessagesSuccessful']:
        #
        #                 msg2 = deliver_goods_obj.order_fulfillment(AmazonOrderId)
        #                 if msg2['MessagesProcessed'] == msg2['MessagesSuccessful']:
        #                     # 第三步  同步成功后 将状态改为发货成功
        #                     OrderStatus = "Shipped"
        #                     deliver_goods_obj.change_SubmitTrackingNumber(AmazonOrderId)
        #                     deliver_goods_obj.change_order_status(AmazonOrderId,OrderStatus)
        #                     return Response({"success_msg":"发货成功"},status=status.HTTP_200_OK)
        #                 else:
        #                     # 如果同步失败   则将状态改为发货失败
        #                     OrderStatus = "ShippedField"
        #                     deliver_goods_obj.change_order_status(AmazonOrderId, OrderStatus)
        #                     return Response({"error_msg": "发货失败"}, status=status.HTTP_400_BAD_REQUEST)
        #             else:
        #                 return Response({"error_msg": "发货失败"}, status=status.HTTP_400_BAD_REQUEST)
        #     else:
        #         return Response({"error_msg":"参数错误"},status=status.HTTP_400_BAD_REQUEST)


class DeliverGoods:

    def __init__(self):
        self.FeedType1 = '_POST_ORDER_ACKNOWLEDGEMENT_DATA_'
        self.FeedType2 = '_POST_ORDER_FULFILLMENT_DATA_'

        self.xml1 = """<?xml version="1.0"?>
        <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
        <Header>
         <DocumentVersion>1.01</DocumentVersion>
         <MerchantIdentifier> M_IDENTIFIER</MerchantIdentifier>
        </Header>
        <MessageType>OrderAcknowledgement</MessageType>"""
        self.xml2 = """<Message>
                 <MessageID>{}</MessageID>
                 <OrderAcknowledgement>
                 <AmazonOrderID>{}</AmazonOrderID>
                 <MerchantOrderID>{}</MerchantOrderID>
                 <StatusCode>{}</StatusCode>
                 <Item>
                 <AmazonOrderItemCode>{}</AmazonOrderItemCode>
                 <MerchantOrderItemID>{}</MerchantOrderItemID>
                 </Item>
                 </OrderAcknowledgement>
                </Message>"""
        self.xml3 = """</AmazonEnvelope>"""

    def get_submit_list_and_result(self, FeedSubmissionId, feeds):
        time.sleep(30)
        number_j = 1
        for j in range(10):
            number_j += 1
            result2 = feeds.get_feed_submission_list(feedids=FeedSubmissionId).original
            submit_result2 = xmltodict.parse(result2)
            if submit_result2['GetFeedSubmissionListResponse']['GetFeedSubmissionListResult']['FeedSubmissionInfo'][
                'FeedProcessingStatus'] == "_DONE_":
                result3 = feeds.get_feed_submission_result(feedid=FeedSubmissionId).original
                submit_result3 = xmltodict.parse(result3)

                return submit_result3['AmazonEnvelope']
            time.sleep(10)
            if number_j > 6:
                return {"error_msg": "请求超时"}


    def order_acknowledgment(self,AmazonOrderID,StatusCode):

        # 获取订单对象
        # AmazonOrderID = request.POST.get('AmazonOrderId')

        # StatusCode = request.POST.get('StatusCode')  # 状态代码:"Success" or "Failure


        # time.sleep(60)
        # return Response({"success_msg": "绑定成功"})
        try:
            order = Orders.objects.get(AmazonOrderId=AmazonOrderID)  # 亚马逊定义的订单商品识别号
        except Exception as e:
            return Response({"error_msg": str(e)})

        MerchantOrderID = order.MerchantOrderID[2:]  # 卖家所定义的订单编码

        # order_items = OrderItem.objects.get(Order=order.id)
        order_items = OrderItem.objects.filter(Order=order.id)
        # if len(order_items) > 1:
        MessageID = 0
        store_id = order.SellerStore.id
        store_info = StoreManagement.objects.get(id=store_id)
        SellerId = store_info.seller_id
        MWSToken = store_info.mws_token
        feed_xml = str()
        xml_str = str()
        for order_item in order_items:
            MessageID += 1
            MerchantOrderItemID = order_item.MerchantOrderItemID[2:]  # 卖家定义的订单商品识别号
            AmazonOrderItemCode = order_item.OrderItemId
            xml_str = self.xml2.format(str(MessageID), AmazonOrderID, MerchantOrderID, StatusCode, AmazonOrderItemCode,
                                  MerchantOrderItemID)
            feed_xml += xml_str

        feed_xml = (self.xml1 + feed_xml + self.xml3)

        feed_xml = feed_xml.encode()

        # 创建用于上传数据的对象
        feeds = Feeds(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
        # 上传数据
        try:
            result1 = feeds.submit_feed(feed=feed_xml, feed_type=self.FeedType1, marketplaceids='ATVPDKIKX0DER').original
        except Exception as e:
            return Response({"error_msg": str(e)})
        FeedSubmissionId = xmltodict.parse(result1)['SubmitFeedResponse']['SubmitFeedResult']['FeedSubmissionInfo'][
            'FeedSubmissionId']
        # time.sleep(30)
        msg = self.get_submit_list_and_result(FeedSubmissionId, feeds)
        msg = msg['Message']['ProcessingReport']['ProcessingSummary']
        return msg

    def order_fulfillment(self,AmazonOrderId):
        feed_xml = """<?xml version="1.0" encoding="UTF-8"?>
                <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amznenvelope.xsd">
                 <Header>
                 <DocumentVersion>1.01</DocumentVersion>
                 <MerchantIdentifier>My Store</MerchantIdentifier>
                 </Header>
                 <MessageType>OrderFulfillment</MessageType>"""
        MessageID = 0
        # AmazonOrderId = request.data.get("AmazonOrderId")

        # time.sleep(60)
        # return Response({"success_msg":"发货成功"})
        order = Orders.objects.filter(AmazonOrderId=AmazonOrderId)
        serializer = OrderFulfillmentSerializer(order, many=True)
        serializer_order = serializer.data[0]

        MerchantOrderID = serializer_order.get("MerchantOrderID")[2:]
        MerchantFulfillmentID = serializer_order.get("MerchantFulfillmentID")[2:]

        FulfillmentDate = str(iosformat.isoformat(datetime.datetime.now() - datetime.timedelta(hours=15))).split(".")[0]

        ShipperTrackingNumber = serializer_order.get("TrackingNumber")
        serializer_orderitem_set = serializer_order.get("orderitem_set")
        for orderitem in serializer_orderitem_set:

            MessageID += 1
            MerchantOrderItemID = orderitem.get("MerchantOrderItemID")[2:]
            MerchantFulfillmentItemID = orderitem.get("MerchantFulfillmentItemID")[2:]
            QuantityShipped = orderitem.get("QuantityOrdered")
            feed_xml_Message = f""" <Message>
         <MessageID>{MessageID}</MessageID>
         <OrderFulfillment>
         <MerchantOrderID>{MerchantOrderID}</MerchantOrderID>
         <MerchantFulfillmentID>{MerchantFulfillmentID}</MerchantFulfillmentID>
         <FulfillmentDate>{FulfillmentDate}</FulfillmentDate>
         <FulfillmentData>
         <CarrierCode>USPS</CarrierCode>
         <ShippingMethod>Second Day</ShippingMethod>
         <ShipperTrackingNumber>{ShipperTrackingNumber}</ShipperTrackingNumber>
         </FulfillmentData>
         <Item>
         <MerchantOrderItemID>{MerchantOrderItemID}</MerchantOrderItemID>
         <MerchantFulfillmentItemID>{MerchantFulfillmentItemID}</MerchantFulfillmentItemID>
         <Quantity>{QuantityShipped}</Quantity>
         </Item>
         </OrderFulfillment>
         </Message>"""
            feed_xml += feed_xml_Message
        store = StoreManagement.objects.get(orders__AmazonOrderId=AmazonOrderId)
        serializer_store = OrderFulfillmentStoreManagementSerializer(store)
        SellerId = serializer_store.data.get("seller_id")
        MWSToken = serializer_store.data.get("mws_token")

        feed_xml += "</AmazonEnvelope>"

        # 创建上传对象
        feeds = Feeds(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
        # 上传数据
        result1 = feeds.submit_feed(feed=feed_xml.encode(), feed_type=self.FeedType2,
                                    marketplaceids='ATVPDKIKX0DER').original

        # 提取上传id
        FeedSubmissionId = xmltodict.parse(result1)['SubmitFeedResponse']['SubmitFeedResult']['FeedSubmissionInfo'][
            'FeedSubmissionId']

        # 查询上传结果
        result2 = self.get_submit_list_and_result(FeedSubmissionId, feeds)
        result2 = result2['Message']['ProcessingReport']['ProcessingSummary']
        return result2

    def change_SubmitTrackingNumber(self,AmazonOrderId):
        order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        order.IsSubmitTrackingNumber = True
        order.save()
    def change_InventedDeliver(self,AmazonOrderId):
        order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        order.IsInventedDeliver = True
        order.save()

    def change_order_status(self, AmazonOrderId,OrderStatus):

        data = dict()
        if OrderStatus == "Shipped":
            data = {"OrderStatus": OrderStatus,
                    "Deal": True,
                    "Examine": True,
                    "Shipped": True}
        elif OrderStatus == 'ShippedWait':
            data = {"OrderStatus": OrderStatus,
                    "Deal": True,
                    "Examine": True,
                    "Shipped": False}
        elif OrderStatus == 'ShippedFailed':
            data = {"OrderStatus": OrderStatus,
                    "Deal": True,
                    "Examine": True,
                    "Shipped": False}
        elif OrderStatus == 'UnBilledFalse':
            data = {"OrderStatus": OrderStatus,
                    "Deal": True,
                    "Examine": True,
                    "Shipped": False}
        try:
            order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        except Exception as e:

            return {"error_msg":str(e)}
        serializer = OrderStatuAndTrackingSeiralizer1(order, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return "状态修改成功"



class OrderAcknowledgment(APIView):
    def post(self, request):

#
#         xml1 = """<?xml version="1.0"?>
# <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
# xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
# <Header>
#  <DocumentVersion>1.01</DocumentVersion>
#  <MerchantIdentifier> M_IDENTIFIER</MerchantIdentifier>
# </Header>
# <MessageType>OrderAcknowledgement</MessageType>"""
#         xml2 = """<Message>
#  <MessageID>{}</MessageID>
#  <OrderAcknowledgement>
#  <AmazonOrderID>{}</AmazonOrderID>
#  <MerchantOrderID>{}</MerchantOrderID>
#  <StatusCode>{}</StatusCode>
#  <Item>
#  <AmazonOrderItemCode>{}</AmazonOrderItemCode>
#  <MerchantOrderItemID>{}</MerchantOrderItemID>
#  </Item>
#  </OrderAcknowledgement>
# </Message>"""
#         xml3 = """</AmazonEnvelope>"""
#     #获取订单对象
#         AmazonOrderID = request.POST.get('AmazonOrderId')
#
#         StatusCode = request.POST.get('StatusCode')  # 状态代码:"Success" or "Failure

#         # time.sleep(60)
#         # return Response({"success_msg": "绑定成功"})
#         try:
#             order = Orders.objects.get(AmazonOrderId=AmazonOrderID)  # 亚马逊定义的订单商品识别号
#         except Exception as e:
#             return Response({"error_msg": str(e)})
#
#         MerchantOrderID = order.MerchantOrderID[2:]  # 卖家所定义的订单编码
#
#         # order_items = OrderItem.objects.get(Order=order.id)
#         order_items = OrderItem.objects.filter(Order=order.id)
#         # if len(order_items) > 1:
#         MessageID = 0
#         store_id = order.SellerStore.id
#         store_info = StoreManagement.objects.get(id=store_id)
#         SellerId = store_info.seller_id
#         MWSToken = store_info.mws_token
#         feed_xml = str()
#         xml_str = str()
#         for order_item in order_items:
#             MessageID += 1
#             MerchantOrderItemID = order_item.MerchantOrderItemID[2:]  # 卖家定义的订单商品识别号
#             AmazonOrderItemCode = order_item.OrderItemId
#             xml_str = xml2.format(str(MessageID), AmazonOrderID, MerchantOrderID, StatusCode,AmazonOrderItemCode, MerchantOrderItemID)
#             feed_xml += xml_str
#
#         feed_xml = (xml1 + feed_xml + xml3)

#         feed_xml = feed_xml.encode()
#
#         # 创建用于上传数据的对象
#         feeds = Feeds(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
#         # 上传数据
#         try:
#             result1 = feeds.submit_feed(feed=feed_xml, feed_type=FeedType1, marketplaceids='ATVPDKIKX0DER').original
#         except Exception as e:
#             return Response({"error_msg": str(e)})
#         FeedSubmissionId = xmltodict.parse(result1)['SubmitFeedResponse']['SubmitFeedResult']['FeedSubmissionInfo']['FeedSubmissionId']
#         # time.sleep(30)
#         msg = get_submit_list_and_result(FeedSubmissionId,feeds)
        # if msg['Message']['ProcessingReport']['ProcessingSummary']['MessagesProcessed'] == msg['Message']['ProcessingReport']['ProcessingSummary']['MessagesSuccessful']:
        #     feed_xml = """<?xml version="1.0" encoding="UTF-8"?>
        #             <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amznenvelope.xsd">
        #              <Header>
        #              <DocumentVersion>1.01</DocumentVersion>
        #              <MerchantIdentifier>My Store</MerchantIdentifier>
        #              </Header>
        #              <MessageType>OrderFulfillment</MessageType>"""
        #     MessageID = 0
        #     AmazonOrderId = AmazonOrderID
        #     # time.sleep(60)
        #     # return Response({"success_msg":"发货成功"})
        #     order = Orders.objects.filter(AmazonOrderId=AmazonOrderId)
        #     serializer = OrderFulfillmentSerializer(order, many=True)
        #     serializer_order = serializer.data[0]

        #     MerchantOrderID = serializer_order.get("MerchantOrderID")[2:]
        #     MerchantFulfillmentID = serializer_order.get("MerchantFulfillmentID")[2:]
        #
        #     FulfillmentDate = \
        #     str(iosformat.isoformat(datetime.datetime.now() - datetime.timedelta(hours=15))).split(".")[0]
        #
        #     ShipperTrackingNumber = serializer_order.get("TrackingNumber")
        #     serializer_orderitem_set = serializer_order.get("orderitem_set")
        #     for orderitem in serializer_orderitem_set:

        #         MessageID += 1
        #         MerchantOrderItemID = orderitem.get("MerchantOrderItemID")[2:]
        #         MerchantFulfillmentItemID = orderitem.get("MerchantFulfillmentItemID")[2:]
        #         QuantityShipped = orderitem.get("QuantityOrdered")
        #         feed_xml_Message = f""" <Message>
        #      <MessageID>{MessageID}</MessageID>
        #      <OrderFulfillment>
        #      <MerchantOrderID>{MerchantOrderID}</MerchantOrderID>
        #      <MerchantFulfillmentID>{MerchantFulfillmentID}</MerchantFulfillmentID>
        #      <FulfillmentDate>{FulfillmentDate}</FulfillmentDate>
        #      <FulfillmentData>
        #      <CarrierCode>USPS</CarrierCode>
        #      <ShippingMethod>Second Day</ShippingMethod>
        #      <ShipperTrackingNumber>{ShipperTrackingNumber}</ShipperTrackingNumber>
        #      </FulfillmentData>
        #      <Item>
        #      <MerchantOrderItemID>{MerchantOrderItemID}</MerchantOrderItemID>
        #      <MerchantFulfillmentItemID>{MerchantFulfillmentItemID}</MerchantFulfillmentItemID>
        #      <Quantity>{QuantityShipped}</Quantity>
        #      </Item>
        #      </OrderFulfillment>
        #      </Message>"""
        #         feed_xml += feed_xml_Message
        #     store = StoreManagement.objects.get(orders__AmazonOrderId=AmazonOrderId)
        #     serializer_store = OrderFulfillmentStoreManagementSerializer(store)
        #     SellerId = serializer_store.data.get("seller_id")
        #     MWSToken = serializer_store.data.get("mws_token")

        #     feed_xml += "</AmazonEnvelope>"

        #     # 创建上传对象
        #     feeds = Feeds(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
        #     # 上传数据
        #     result1 = feeds.submit_feed(feed=feed_xml.encode(), feed_type=FeedType2,
        #                                 marketplaceids='ATVPDKIKX0DER').original

        #     # 提取上传id
        #     FeedSubmissionId = xmltodict.parse(result1)['SubmitFeedResponse']['SubmitFeedResult']['FeedSubmissionInfo'][
        #         'FeedSubmissionId']

        #     # 查询上传结果
        #     result2 = get_submit_list_and_result(FeedSubmissionId, feeds)
        #     if result2['Message']['ProcessingReport']['ProcessingSummary']['MessagesProcessed'] == result2['Message']['ProcessingReport']['ProcessingSummary']['MessagesSuccessful']:
        #         pass
        return Response("ok")

class OrderFulfillment(APIView):

    def post(self, request):

 #
 #        feed_xml = """<?xml version="1.0" encoding="UTF-8"?>
 #        <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amznenvelope.xsd">
 #         <Header>
 #         <DocumentVersion>1.01</DocumentVersion>
 #         <MerchantIdentifier>My Store</MerchantIdentifier>
 #         </Header>
 #         <MessageType>OrderFulfillment</MessageType>"""
 #        MessageID = 0
 #        AmazonOrderId = request.data.get("AmazonOrderId")

 #        # time.sleep(60)
 #        # return Response({"success_msg":"发货成功"})
 #        order = Orders.objects.filter(AmazonOrderId=AmazonOrderId)
 #        serializer = OrderFulfillmentSerializer(order, many=True)
 #        serializer_order = serializer.data[0]

 #        MerchantOrderID = serializer_order.get("MerchantOrderID")[2:]
 #        MerchantFulfillmentID = serializer_order.get("MerchantFulfillmentID")[2:]
 #
 #        FulfillmentDate = str(iosformat.isoformat(datetime.datetime.now()-datetime.timedelta(hours=15))).split(".")[0]
 #
 #        ShipperTrackingNumber = serializer_order.get("TrackingNumber")
 #        serializer_orderitem_set = serializer_order.get("orderitem_set")
 #        for orderitem in serializer_orderitem_set:
 #            MessageID += 1
 #            MerchantOrderItemID = orderitem.get("MerchantOrderItemID")[2:]
 #            MerchantFulfillmentItemID = orderitem.get("MerchantFulfillmentItemID")[2:]
 #            QuantityShipped = orderitem.get("QuantityOrdered")
 #            feed_xml_Message = f""" <Message>
 # <MessageID>{MessageID}</MessageID>
 # <OrderFulfillment>
 # <MerchantOrderID>{MerchantOrderID}</MerchantOrderID>
 # <MerchantFulfillmentID>{MerchantFulfillmentID}</MerchantFulfillmentID>
 # <FulfillmentDate>{FulfillmentDate}</FulfillmentDate>
 # <FulfillmentData>
 # <CarrierCode>USPS</CarrierCode>
 # <ShippingMethod>Second Day</ShippingMethod>
 # <ShipperTrackingNumber>{ShipperTrackingNumber}</ShipperTrackingNumber>
 # </FulfillmentData>
 # <Item>
 # <MerchantOrderItemID>{MerchantOrderItemID}</MerchantOrderItemID>
 # <MerchantFulfillmentItemID>{MerchantFulfillmentItemID}</MerchantFulfillmentItemID>
 # <Quantity>{QuantityShipped}</Quantity>
 # </Item>
 # </OrderFulfillment>
 # </Message>"""
 #            feed_xml += feed_xml_Message
 #        store = StoreManagement.objects.get(orders__AmazonOrderId=AmazonOrderId)
 #        serializer_store = OrderFulfillmentStoreManagementSerializer(store)
 #        SellerId = serializer_store.data.get("seller_id")
 #        MWSToken = serializer_store.data.get("mws_token")

 #        feed_xml += "</AmazonEnvelope>"

 #        # 创建上传对象
 #        feeds = Feeds(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
 #        # 上传数据
 #        result1 = feeds.submit_feed(feed=feed_xml.encode(), feed_type=FeedType2,
 #                                    marketplaceids='ATVPDKIKX0DER').original

 #        # 提取上传id
 #        FeedSubmissionId = xmltodict.parse(result1)['SubmitFeedResponse']['SubmitFeedResult']['FeedSubmissionInfo'][
 #            'FeedSubmissionId']

 #        # 查询上传结果
 #        result2 = get_submit_list_and_result(FeedSubmissionId, feeds)

        return Response({"success_msg": "发货成功", "order_msg": "ok"})
    



# class OrderFulfillment(APIView):
#      def post(self,request):
#          #获取请求体数据
#          AmazonOrderId = request.POST.get("AmazonOrderId")
#          MessageID = request.POST.get('MessageID')  # 提交信息编号
#          FulfillmentDate = request.POST.get('FulfillmentDate')  # 物品实际运送或取货的日期，具体取决于履行情况 样例：2002-05-01T15:36:33-08:00
#          CarrierCode = request.POST.get('CarrierCode')  #运输承运商代码（快递商）样例：USPS
#          ShippingMethod = request.POST.get('ShippingMethod')  #邮寄方式 样例：First Class
#          ShipperTrackingNumber = request.POST.get('ShipperTrackingNumber')  #跟踪货件的编号（运单号）
#          Quantity = request.POST.get('Quantity')  #发货数量
#
#          order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
#          MerchantOrderID = order.MerchantOrderID[2:]  # 卖家所定义的订单编码
#          MerchantOrderItemID = order.MerchantOrderItemID[2:]  # 卖方为订单中的商品提供的可选ID
#          MerchantFulfillmentID = order.MerchantFulfillmentID[2:]  # 卖方提供的货件唯一标识符（亚马逊未使用）
#          MerchantFulfillmentItemID = order.MerchantFulfillmentItemID[2:]  #卖方提供的商品的唯一标识符装运（亚马逊不使用）
#          store_id = order.SellerStore.id
#          store_info = StoreManagement.objects.get(id=store_id)
#          SellerId = store_info.seller_id
#          MWSToken = store_info.mws_token
#          # 拼接XML格式上传数据
#
#          feed_xml = feed_xml_module2.format(MessageID,MerchantOrderID,MerchantFulfillmentID,FulfillmentDate,CarrierCode,ShippingMethod,ShipperTrackingNumber,MerchantOrderItemID,MerchantFulfillmentItemID,Quantity).encode()
#          #创建上传对象
#          feeds = Feeds(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
#          #上传数据
#          result1 = feeds.submit_feed(feed=feed_xml, feed_type=FeedType2, marketplaceids='ATVPDKIKX0DER').original
#          #提取上传id
#          FeedSubmissionId = xmltodict.parse(result1)['SubmitFeedResponse']['SubmitFeedResult']['FeedSubmissionInfo']['FeedSubmissionId']
#          number_j = 1
#
#          get_submit_list_and_result(FeedSubmissionId,feeds)
#
#          return Response({"success_msg": "发货成功"})


"""云图物流接口"""
from orders.utils import Yuntu, ImageMethod


class CreateOrder(APIView):
    """申请运单   并将运单号入库"""
    permission_classes = [IsAuthenticated]
    def post(self,request):
        AmazonOrderIdList = request.data  # 获取订单ID列表

        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------对{AmazonOrderIdList}申请运单------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        data = []
        for AmazonOrderId in AmazonOrderIdList:
            try:
                order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
            except Exception as e:
                return Response({'error_msg': str(e)})
            item = {}
            item['CustomerOrderNumber'] = order.TQName  # 客户订单号,不能重复
            item['ShippingMethodCode'] = "EUB-FZ"  # 运输方式代码 暂时默认 云途物流-福州EUB
             #获取订单对象
            # 获取订单详情
            try:
                order_items = OrderItem.objects.filter(Order=order.id)
            except Exception as e:
                return Response({'error_msg': str(e)})
            address_serializer = OrderAddressSerializer(order)
            address_id = address_serializer.data['ShippingAddress']
            address = Address.objects.get(id=address_id)
            # 获取地址对象address
            CountryCode = address.CountryCode  # 收件人所在国家，填写国际通用标准2位简码
            FirstName = address.Name  # 收件人姓(这里填的是姓名）
            Street = address.AddressLine1  # 收件人详细地址
            City = address.City  # 收件人所在城市
            State = address.StateOrRegion  # 收件人省州是必填项
            Zip = address.PostalCode  # 收件人邮编
            Phone = address.Phone  # 收件人电话

            item['Receiver'] = {}
            item['Receiver']['CountryCode'] = CountryCode
            item['Receiver']['FirstName'] = FirstName
            item['Receiver']['Street'] = Street
            item['Receiver']['City'] = City
            item['Receiver']['State'] = State
            item['Receiver']['Zip'] = Zip
            item['Receiver']['Phone'] = Phone or 12345678


            #申报信息
            item['Parcels'] = []

            PackageCount = 0    # 运单包裹的件数，必须大于0的整数
            Weight = 0          # 必填	预估包裹总重量，单位kg,最多3位小数
            for order_item in order_items:

                PackageCount += 1
                customs_dec_serializer = OrderItemCustomDec(order_item)
                customs_dec_id = customs_dec_serializer.data['CustomsDeclarationInfo']
                try:
                    customsdeclarationinfos = CustomsDeclarationInfos.objects.get(id=customs_dec_id)
                except Exception as e:
                    return Response({"error_msg": "报关信息不存在"})

                #获取报关
                EName = customsdeclarationinfos.EnglishCustomsDeclaration  # 英文报关
                CName = customsdeclarationinfos.ChineseCustomsDeclaration  # 中文报关
                UnitPrice = customsdeclarationinfos.Price    # 申报价格
                UnitWeight = float(customsdeclarationinfos.Weight)/1000  # 申报重量

                Quantity = customs_dec_serializer.data["QuantityOrdered"]     # 申报数量
                Weight += (float(UnitWeight) * int(Quantity))
                ParcelsDict = dict()
                ParcelsDict['EName'] = EName
                ParcelsDict['CName'] = CName
                ParcelsDict['UnitPrice'] = UnitPrice
                ParcelsDict['UnitWeight'] = UnitWeight
                ParcelsDict['Quantity'] = Quantity
                ParcelsDict['Weight'] = Weight
                item['Parcels'].append(ParcelsDict)
            # adress =
            # serializer_of_adress = OrderAdressSerializer

            CustomerOrderNumber = AmazonOrderId  # 客户订单号,不能重复
            ShippingMethodCode = "EUB-FZ"  # 运输方式代码 暂时默认 云途物流-福州EUB

            item['PackageCount'] = PackageCount
            item['Weight'] = "%.1f" % Weight

            data.append(item)

        data = json.dumps(data)  # 把列表转成json
        # yt = Yuntu('C05526', 'PK0LgIrnCSM=')  # 创建云途物流对象
        yt = Yuntu('C06620', '8HLmJxgw3+w=')
        result = yt.createorder(data)  #申请运单
        result = json.loads(result)

        if result['Message'] == "提交成功":

            for TrackInfo in result['Item']:

                AmazonOrderIdForTrack = TrackInfo['CustomerOrderNumber']
                TrackingNumber = TrackInfo['TrackingNumber']
                order_for_track = Orders.objects.get(TQName=AmazonOrderIdForTrack)
                serializer_for_tracking = TrackingNumSerializer(data={"TrackingNumber":TrackingNumber})
                serializer_for_tracking.is_valid()
                order_for_track.TrackingNumber = serializer_for_tracking.data["TrackingNumber"]
                order_for_track.ApplicationOrderNumber = True
                order_for_track.save()

            return Response(result['Item'][0]['TrackingNumber'])
        elif result['Message'] == "参数错误":
            return Response(result["Message"])
        elif result['Message'] == "部分成功":
            error_list = list()
            for i in result['Item']:
                if i['Remark'] is not None:
                    error_list.append(i['CustomerOrderNumber']+i['Remark'])
                else:
                    error_list.append(i['CustomerOrderNumber']+'申请成功')

            return Response(error_list)

        return Response(result)# 返回结果
        # return Response(data)


#api参数示例["LT922713538CN","LT924179396CN"]
import re
class LabelPrint(APIView):
    permission_classes = [IsAuthenticated]
    def get(self,request):

        Orders.objects.all().delete()
        Address.objects.all().delete()
        PaymentMethodDDetails.objects.all().delete()
        OrdersMoney.objects.all().delete()

        OrderItem.objects.all().delete()
        TaxCollection.objects.all().delete()
        ProductInfos.objects.all().delete()
        OrdersItemMoney.objects.all().delete()

        return Response("ok")

    def post(self,request):

        datas = request.data


        if not isinstance(datas,dict):
            return Response({"error_msg": "数据类型错误"}, status=status.HTTP_400_BAD_REQUEST)
        TrackingNumberList = datas.get("TrackingNumberList")

        # if len([i for i in TrackingNumberList if i]) == 0:
        #     return Response({"error_msg": "没有运单号"})
        if not isinstance(TrackingNumberList,list):
            return Response({"error_msg":"数据类型错误"}, status=status.HTTP_400_BAD_REQUEST)
        if len(TrackingNumberList) == 0:
            return Response({"error_msg": "缺少数据"}, status=status.HTTP_400_BAD_REQUEST)
        for i in TrackingNumberList:
            if i == '':
                return Response({"error_msg": "没有运单号"})

            else:
                try:
                    order = Orders.objects.get(TrackingNumber=i)
                except Exception as e:
                    return Response({'error_msg': str(e)},status=status.HTTP_404_NOT_FOUND)
                order.FaceSheet = True
                order.save()
        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------对{TrackingNumberList}进行打印面单------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        data = json.dumps(TrackingNumberList)
        # yt = Yuntu('C05526', 'PK0LgIrnCSM=')  # 创建云途物流对象
        yt = Yuntu('C06620', '8HLmJxgw3+w=')
        result = yt.labelprint(data)  # 标签打印
        result = json.loads(result)

        labelprintpdf = result['Item'][0]['Url']
        return Response(labelprintpdf)  # 返回pdf格式


# 导表
# 1.导出excel的库
import xlwt
# 2.实现了在内存中读写bytes
from io import BytesIO


class ExportOrders(APIView):
    """导出订单"""
    # def post(self, request):
    #     request_data = request.data
    #
    #     AmazonOrderIds = request_data.get('AmazonOrderIds')
    #     ExportKeys = request_data.get('ExportKeys')
    def get(self, request):
        params = request.query_params
        print(params)
        print(params.get('AmazonOrderIds'))
        # AmazonOrderIds = json.loads(params.get('AmazonOrderIds'))
        # ExportKeys = json.loads(params.get('ExportKeys'))
        AmazonOrderIds = params.get('AmazonOrderIds').split(",")
        ExportKeys = params.get('ExportKeys').split(",")
        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------对{AmazonOrderIds}进行了导出订单操作------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        orders = Orders.objects.filter(AmazonOrderId__in=AmazonOrderIds)
        serializer_orders = ExportOrdersSerializer(orders, many=True)
        serializer_orders_data = serializer_orders.data
        # 设置HTTPResponse的类型
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment;filename=orders.xls'
        # 创建一个文件对象
        wb = xlwt.Workbook(encoding='utf8')
        # 创建一个sheet对象
        # sheet = wb.add_sheet('order-sheet')
        sheet = wb.add_sheet('订单列表')
        # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改
        style_heading = xlwt.easyxf("""
                            font:
                                name Arial,
                                colour_index white,
                                bold on,
                                height 0xA0;
                            align:
                                wrap off,
                                vert center,
                                horiz center;
                            pattern:
                                pattern solid,
                                fore-colour 000000;
                            borders:
                                left THIN,
                                right THIN,
                                top THIN,
                                bottom THIN;
                            """)
        # 写入文件标题
        sheet_title = {"AmazonOrderId": "订单ID", "PurchaseDate": "下单日期", "OrderStatus": "订单状态", "store": "店铺名",
                       "orderState": "平台渠道", "MarketplaceId": "商城的匿名编码",
                       "CurrencyCode": "货币代码", "Amount": "货币金额", "TrackingNumber": "运单跟踪号", "OrderItemId": "商品识别号",
                       "ASIN": "ASIN",
                       "SellerSKU": "卖家SKU", "Title": "商品名称", "QuantityShipped": "商品数量", "GoodsImage": "商品图片",
                       "BuyerEmail": "买家邮箱", "BuyerName": "买家姓名", "Name": "收件人姓名", "City": "收件人城市",
                       "PostalCode": "收件人邮编", "CountryCode": "国家二字代码", "ChineseCustomsDeclaration": "中文报关",
                       "EnglishCustomsDeclaration": "英文报关", "Weight": "重量", "Price": "价格", "CustomsCode": "海关编码",
                       "IsElectric": "是否带电"}
        default_field = {"orderState": "amazon"}
        orders_field = ["AmazonOrderId", "PurchaseDate", "OrderStatus", "TrackingNumber", "MarketplaceId", "BuyerEmail",
                        "BuyerName"]
        OrderTotal_field = ["CurrencyCode", "Amount"]
        orderitem_set_field = ["OrderItemId", "ASIN", "SellerSKU", "Title", "QuantityShipped", "GoodsImage"]
        SellerStore_field = ["store"]
        ShippingAddress_field = ["Name", "City", "PostalCode", "CountryCode", "Phone"]
        CustomsDeclarationInfos_field = ["ChineseCustomsDeclaration", "EnglishCustomsDeclaration", "Weight", "Price",
                                         "CustomsCode", "IsElectric"]
        # 写入文件内容
        sheet_title_row = 0
        sheet_title_column = 0
        for i in ExportKeys:
            sheet.write(sheet_title_row, sheet_title_column, sheet_title.get(i), style_heading)
            sheet_title_column += 1
        sheet_content_row = 1
        for i in serializer_orders_data:
            sheet_content_column = 0
            for j in ExportKeys:
                if j in orders_field:
                    sheet.write(sheet_content_row, sheet_content_column, i[j])
                    sheet_content_column += 1
                elif j in OrderTotal_field:
                    sheet.write(sheet_content_row, sheet_content_column, i["OrderTotal"][j])
                    sheet_content_column += 1
                elif j in SellerStore_field:
                    sheet.write(sheet_content_row, sheet_content_column, i["SellerStore"][j])
                    sheet_content_column += 1
                elif j in ShippingAddress_field:
                    sheet.write(sheet_content_row, sheet_content_column, i["ShippingAddress"][j])
                    sheet_content_column += 1
                elif j in default_field:
                    sheet.write(sheet_content_row, sheet_content_column, default_field[j])
                    sheet_content_column += 1
                elif j in orderitem_set_field:
                    sheet_content = ''
                    for k in i["orderitem_set"]:
                        sheet_content += k[j] + '\n'
                    sheet_content.rstrip('\n')

                    sheet.write(sheet_content_row, sheet_content_column, sheet_content)
                    sheet_content_column += 1
                elif j in CustomsDeclarationInfos_field:
                    sheet_content = ''
                    for k in i["orderitem_set"]:
                        if k["CustomsDeclarationInfo"]:
                            content = k["CustomsDeclarationInfo"][j]
                        else:
                            content = ''
                        if type(content) == bool:
                            if content:
                                content = '是'
                            else:
                                content = '否'

                        sheet_content += content + '\n'
                    sheet_content.rstrip('\n')

                    sheet.write(sheet_content_row, sheet_content_column, sheet_content)
                    sheet_content_column += 1
            sheet_content_row += 1

        wb.save('Excel_test.xls')
        # 写出到IO
        output = BytesIO()
        wb.save(output)
        # 重新定位到开始
        output.seek(0)
        response.write(output.getvalue())
        return response

        # return Response(serializer_orders_data)


class GetNumberOfOrder(APIView):
    def get(self, request):
        """获取订单栏目的数量"""
        All = Orders.objects.count()
        Unshipped = Orders.objects.filter(OrderStatus="Unshipped").count()
        UnDealed = Orders.objects.filter(OrderStatus="UnDealed").count()
        UnBilledTrue = Orders.objects.filter(OrderStatus="UnBilledTrue").count()
        UnBilledFalse = Orders.objects.filter(OrderStatus="UnBilledFalse").count()
        Shipped = Orders.objects.filter(OrderStatus="Shipped").count()
        ShippedFailed = Orders.objects.filter(OrderStatus="ShippedFailed").count()
        ShippedWait = Orders.objects.filter(OrderStatus="ShippedWait").count()
        Canceled = Orders.objects.filter(OrderStatus="Canceled").count()
        LayAside = Orders.objects.filter(OrderStatus="LayAside").count()
        return_msg = {
            "All": All,
            "Unshipped": Unshipped,
            "UnDealed": UnDealed,
            "UnBilledTrue": UnBilledTrue,
            "UnBilledFalse": UnBilledFalse,
            "Shipped": Shipped,
            "ShippedFailed": ShippedFailed,
            "ShippedWait": ShippedWait,
            "Canceled": Canceled,
            "LayAside": LayAside,
        }
        return Response(return_msg, status=status.HTTP_200_OK)


class GetTrueFinance(APIView):
    def get(self,request):

        # ******************************************************************************************************
        access_key = 'AKIAITNXOMXBNOGOAHMQ'
        secret_key = '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'
        SellerId = "A1V087CKPQPJAJ"
        MWSToken = "amzn.mws.fab6a111-4a7b-3a35-7d14-9cbc6ac30a0a"

        # order_update_time = datetime.datetime(2019, 7, 1)
        #
        # CreatedAfter = isoformat(order_update_time)
        #
        x = mws.Reports(access_key=access_key, secret_key=secret_key, account_id=str(SellerId),
                        auth_token=str(MWSToken))
        try:
            # orders = x.list_orders(created_after=CreatedAfter, marketplaceids=marketplaceids)
            orders = x.get_report(report_id='16985645627018178')
        except Exception as e:
            print(str(e))

        response_data = orders.original
        datas = xmltodict.parse(response_data)

        # data = mws.DictWrapper(response_data, None)
        # data = data.parsed

        return Response(datas)


class UpdateShippingAddress(APIView):
    permission_classes = [IsAuthenticated]
    def post(self, request):
        """修改收货地址"""
        datas = request.data
        id = datas.get("id")

        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------对{id}进行修改地址------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        address_obj = Address.objects.get(id=id)

        serializer = ShippingAddressSerializers1(address_obj,data=datas)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"success_msg":"修改地址信息成功"}, status=status.HTTP_200_OK)

class UpdateTrackingNumber(APIView):
    permission_classes = [IsAuthenticated]
    def post(self, request):
        data = request.data
        AmazonOrderId = data.get("AmazonOrderId")
        TrackingNumber = data.get("TrackingNumber")

        if TrackingNumber:
            order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
            datas = {"TrackingNumber":TrackingNumber}
            serializer = TrackingNumberSerializer(order, data=datas)
            serializer.is_valid()
            serializer.save()
            order.ApplicationOrderNumber = True
            order.save()
        else:
            return Response({"error_msg":"参数有误"}, status=status.HTTP_404_NOT_FOUND)

        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------对{AmazonOrderId}修改运单号------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))
        return Response({"success_msg": "修改运单号成功"}, status=status.HTTP_200_OK)

class UpdateTQName(APIView):
    permission_classes = [IsAuthenticated]

    def get(self,request):
        """
        修改唯一编号
        1 修改唯一编号   当修改了唯一编号原始的运单号就不能再使用了

        """
        parms = request.query_params  # 获取查询参数
        AmazonOrderId = parms.get('AmazonOrderId')  # 获取用户ID

        order = Orders.objects.get(AmazonOrderId=AmazonOrderId)
        TQName = "TQ" + ''.join(str(uuid.uuid1()).split('-'))[6:20].upper() + ''.join(random.sample(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 5))
        datas = {"TQName": TQName, "TrackingNumber": ""}
        serializer = TQNameSerializer(order,data=datas)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        order.IsSubmitTrackingNumber = False
        order.ApplicationOrderNumber = False
        order.save()
        # 使用redis记录操作和时间
        operation_log_time = datetime.datetime.now()
        operation_log_user = request.user.username
        action = f"{operation_log_user}------对{AmazonOrderId}进行更换包裹号------{operation_log_time}"
        redis = get_redis_connection('order_update_info')
        redis.rpush("operation_log", f'{action}'.encode("GBK"))

        return Response({"success_msg":TQName})

class DeleteOneOrderView(APIView):
    def get(self,request):
        parms = request.query_params  # 获取查询参数
        AmazonOrderId = parms.get('AmazonOrderId')  # 获取用户ID
        Orders.objects.get(AmazonOrderId=AmazonOrderId).delete()
        return Response("delete success")




# 开启定时工作
try:
    # 实例化调度器
    scheduler = BackgroundScheduler()
    # 调度器使用DjangoJobStore()
    scheduler.add_jobstore(DjangoJobStore(), "default")
    # 设置定时任务，选择方式为interval，时间间隔为10s
    # 另一种方式为每天固定时间执行任务，对应代码为：
    # @register_job(scheduler, 'cron', day_of_week='mon-fri', hour='9', minute='30', second='10',id='task_time')

    @register_job(scheduler, "interval", seconds=2700)
    def update_order_status():
        task = MysqlOfOrderUpdate()
        store_list = task.get_store_list()
        max_num = len(store_list)
        order_list = list()
        for i in range(0, max_num):
            order = task.update_orders_except_shipped(store_list[i])
            if isinstance(order, dict):
                order_list.append(order)
            else:
                order_list += order

        for j in order_list:
            if j['OrderStatus'] != "Unshipped":
                order_obj = Orders.objects.get(AmazonOrderId=j['AmazonOrderId'])
                order_obj.OrderStatus = j['OrderStatus']
                order_obj.save()

    """更新OrderItem中GoodsImage字段"""
    @register_job(scheduler, "interval", seconds=2700)
    def update_order_item_image_filed():
        access_key = 'AKIAJGOQGGTWX4ICHVZQ'
        secret_key = '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'
        SellerId = "APW1B548Y33A8"
        MWSToken = "amzn.mws.04b60bef-32f8-aa27-0820-c6802871b4e0"
        marketplaceid_list = {
            "Amazon.ca": "A2EUQ1WTGCTBG2",
            "Amazon.com": "ATVPDKIKX0DER",
            "Amazon.com.mx": "A1AM78C64UM0Y8",
        }
        order_items = OrderItem.objects.filter(GoodsImage='')
        serializer = OrderItemForSKUSerializer(order_items, many=True)

        # data_list = list()
        i = 0
        for order_item in serializer.data:

            order = Orders.objects.get(id=order_item['Order'])

            # ASIN_list.append(order_item.ASIN)
            x = mws.Products(access_key=access_key, secret_key=secret_key, account_id=SellerId, auth_token=MWSToken)
            amazondatas = x.get_matching_product_for_id(marketplaceid=marketplaceid_list[order.SalesChannel],
                                                        type_="ASIN", ids=order_item['ASIN'])
            response_data = amazondatas.original
            xml_dict = xmltodict.parse(response_data)

            if xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['@status'] == 'ClientError':
                orderitem = OrderItem.objects.get(id=order_item['id'])
                orderitem.GoodsImage = "http://47.52.228.7:8080/dist/kong.png"
                orderitem.save()
                continue
            else:
                # data_list.append(xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['AttributeSets']['ns2:ItemAttributes']["ns2:SmallImage"]['ns2:URL'])
                orderitem = OrderItem.objects.get(id=order_item['id'])
                orderitem.GoodsImage = xml_dict['GetMatchingProductForIdResponse']['GetMatchingProductForIdResult']['Products']['Product']['AttributeSets']['ns2:ItemAttributes']["ns2:SmallImage"]['ns2:URL']
                orderitem.save()


    @register_job(scheduler, "interval", seconds=360)
    def update_goods_ranking():   # 更新商品排名数据统计
        GoodsRank.objects.all().delete()
        order_items = OrderItem.objects.exclude(QuantityShipped=0)
        serializer_goods = GoodsItemSerializer(order_items, many=True)
        data_dict_list = list()
        data_dict = dict()
        for i in serializer_goods.data:
            data_dict['Image'] = i['GoodsImage']
            data_dict['title'] = i['Title']
            data_dict['StoreName'] = i['Order']['SellerStore']['store']
            data_dict['SellerSKU'] = i['SellerSKU']
            data_dict['ASIN'] = i['ASIN']
            data_dict['Time'] = i['Order']['PurchaseDate']
            data_dict['sell_numb'] = i['QuantityShipped']
            data_dict['goods_price'] = i['ItemPrice']['Amount']
            data_dict['SalesChannel'] = i['Order']['SalesChannel']
            create_goods_rank_serialzier = GoodsRankSerializer(data=data_dict)
            create_goods_rank_serialzier.is_valid()
            create_goods_rank_serialzier.save()


    @register_job(scheduler, "interval", seconds=1800)
    def my_job():
        # 这里写你要执行的任务
        task = MysqlOfOrderUpdate()
        store_list = task.get_store_list()

        max_num = len(store_list)
        # 每次更新redis 之前先将new变为old数据  再将new数据删除
        # 更新时 将更新的数据一条一条加入new中
        # 在返回前端数据时返回new数据， 在更新的时候返回old数据
        storename_list = [store.store for store in store_list]
        redis = get_redis_connection('order_update_info')
        pl = redis.pipeline()
        for j in storename_list:

            if pl.exists(f"new_{j}") is True:

                pass
            else:
                pl.rpush(f"new_{j}", f'{j}暂无订单更新'.encode("GBK"))

            if pl.exists(f"old_{j}") is True:
                pass
            else:
                pl.rpush(f"old_{j}", f'{j}暂无订单更新'.encode("GBK"))

            pl.delete(f"old_{j}")

            pl.rename(f"new_{j}", f"old_{j}")

        pl.execute()


        for i in range(max_num):
            task.let_mysql_order_update(store_list[i])


    register_events(scheduler)
    scheduler.start()
except Exception as e:
    # 有错误就停止定时器
    scheduler.shutdown()
